使用mod_rewrite将动态数字路径转发至子目录
Solution for Your .htaccess Rewrite Need
Hey there! As someone new to .htaccess, it's totally normal to feel stuck figuring out the right search terms—let's break this down step by step so you can get the redirect working exactly how you want.
What You'll Need to Do
First, make sure your Apache server has mod_rewrite enabled (most shared hosts have this turned on by default, but if you're managing your own server, you might need to enable it via Apache config). Then, edit or create a .htaccess file in your website's root directory (the same folder where your main index.html/index.php lives) and add these rules:
RewriteEngine On RewriteRule ^(\d+)$ /folder1/folder2/$1 [L,R=301]
Let's Break Down Each Part
RewriteEngine On: This turns on the URL rewriting engine—you need this first, otherwise none of the rewrite rules will work.^(\d+)$: This is the pattern we're matching.^marks the start of the URL path,$marks the end.\d+matches one or more digits (exactly what you need for URLs like/2057).- The parentheses
()"capture" the digits so we can reuse them later as$1.
/folder1/folder2/$1: This is where we're sending the user.$1replaces itself with the digits we captured from the original URL.[L,R=301]:Ltells Apache this is the last rule to process for this request (prevents other rules from interfering).R=301is a permanent redirect—this tells search engines that the old URL has permanently moved to the new one, which is good for SEO. If you're just testing and want a temporary redirect, useR=302instead.
Quick Notes to Avoid Headaches
- Make sure your
.htaccessfile is named correctly (it starts with a dot, no extra extensions like.txt). - Clear your browser cache after setting this up—301 redirects get cached, so you might not see changes right away unless you do this.
- If you already have other rewrite rules in your
.htaccess, put this one at the top to make sure it runs first.
内容的提问来源于stack exchange,提问作者Thor
相关产品推荐
相关产品推荐

