PHP博客网站友好URL配置咨询:当前URL转目标格式
Hey there! Let's get those clean, user-friendly URLs working for your blog. Your initial RewriteRule is on the right track, but we need to tweak a few things and cover some prerequisites to make it function properly. Here's a step-by-step guide:
1. Make Sure mod_rewrite is Enabled
First off, Apache's mod_rewrite module needs to be turned on for any rewrite rules to work.
- Check your Apache configuration file (usually
httpd.conforapache2.conf) and look for this line:
If it's commented out (starts withLoadModule rewrite_module modules/mod_rewrite.so#), remove the#to enable it, then restart Apache. - Alternatively, create a quick
phpinfo.phpfile with<?php phpinfo(); ?>and check if "mod_rewrite" appears under the Apache modules section.
2. Place .htaccess in the Correct Directory
Since your blog lives in the /abc subdirectory, your .htaccess file must be inside the /abc folder, not the root of your domain. Also, ensure your Apache config allows overrides for this directory:
In your site's virtual host or main Apache config, set:
<Directory "/path/to/your/abc/folder"> AllowOverride All </Directory>
Restart Apache after making this change.
3. Update Your Rewrite Rules
Here's the adjusted rule set you should use in your /abc/.htaccess file:
RewriteEngine On # Set the base directory for rewrites (critical for subdirectories!) RewriteBase /abc/ # Rewrite friendly URL to the actual PHP file RewriteRule ^blog-detail/([0-9]+)/?$ blog-detail.php?id=$1 [NC,L] # Optional: Redirect old URL format to the friendly one (for SEO) RewriteCond %{THE_REQUEST} ^GET\ /abc/blog-detail\.php\?id=([0-9]+) [NC] RewriteRule ^ blog-detail/%1? [R=301,L]
Let me break this down:
RewriteBase /abc/: Tells Apache that all rewrite rules are relative to the/abcsubdirectory, preventing broken paths.^blog-detail/([0-9]+)/?$: The/?makes the trailing slash optional (so both/blog-detail/1and/blog-detail/1/work). The([0-9]+)captures numeric IDs only.[NC,L]:NCmakes the rule case-insensitive,Ltells Apache to stop processing further rules if this one matches.- The second rule pair redirects any requests to the old
blog-detail.php?id=1format to the friendly URL, using a 301 (permanent) redirect which helps with search engine rankings.
4. Verify PHP Still Gets the ID
You don't need to change anything in your blog-detail.php file—you can still access the ID using $_GET['id'] as you did before.
5. Test and Debug
- Try visiting
xyz.com/abc/blog-detail/1—it should load the same content asxyz.com/abc/blog-detail.php?id=1. - If it doesn't work, check Apache's error logs (usually located at
/var/log/apache2/error.logon Linux systems) for clues about what's going wrong. Common issues include missingmod_rewrite, incorrectAllowOverridesettings, or typos in the rule.
内容的提问来源于stack exchange,提问作者Rohit Rajan




