如何在PHP中实现子URL重写?已尝试.htaccess但无效
Hey there! Sorry to hear your .htaccess rewrite rules aren’t hitting the mark—let’s work through this together.
First up, it’d be super helpful if you shared specific examples of the original sub-URL format you’re trying to rewrite and the target format you want to land on. That said, let’s cover the most common roadblocks and working examples to get you moving:
1. Ensure mod_rewrite is enabled
A lot of the time, rewrite rules fail simply because the Apache mod_rewrite module isn’t turned on:
- For Ubuntu/Debian systems: Run
sudo a2enmod rewritethen restart Apache withsudo systemctl restart apache2. - For XAMPP/WAMP (Windows): Open your
httpd.conffile, remove the#from#LoadModule rewrite_module modules/mod_rewrite.so, then restart your server.
2. Verify .htaccess setup
Your .htaccess file needs to be in your website’s root directory, with permissions set to something the server can read (like 644). Also, double-check your Apache config (httpd.conf or virtual host file) has AllowOverride All set for your site’s directory—if it’s set to None, Apache will ignore your .htaccess rules entirely.
3. Working Rule Examples (Based on Common Use Cases)
Let’s use a couple of typical scenarios to show how rules work:
Scenario 1: Rewrite example.com/product.php?id=123 to example.com/product/123
RewriteEngine On # Optional: Redirect old URL to new one (good for SEO, sends 301 permanent redirect) RewriteCond %{THE_REQUEST} /product\.php\?id=([0-9]+) [NC] RewriteRule ^ /product/%1? [R=301,L] # Rewrite the "pretty" URL back to the actual PHP file (internal rewrite) RewriteRule ^product/([0-9]+)$ product.php?id=$1 [L]
[NC]makes the rule case-insensitive[R=301,L]tells Apache to send a 301 redirect and stop processing further rules- The
?at the end of the redirect URL strips off the original query string
Scenario 2: Rewrite example.com/category.php?cat=laptops&page=3 to example.com/category/laptops/page/3
RewriteEngine On RewriteCond %{THE_REQUEST} /category\.php\?cat=([^&]+)&page=([0-9]+) [NC] RewriteRule ^ /category/%1/page/%2? [R=301,L] RewriteRule ^category/([^/]+)/page/([0-9]+)$ category.php?cat=$1&page=$2 [L]
4. Debugging Your Rules
If rules still aren’t working, enable rewrite logging to see what’s happening:
- For Apache 2.2 and older: Add these lines to your .htaccess (update the log path to a location your server can write to):
RewriteLog "/var/log/apache2/rewrite.log" RewriteLogLevel 3 - For Apache 2.4+: Add this to your Apache config (not .htaccess for better performance):
LogLevel alert rewrite:trace3
The log will show exactly how Apache is processing your rules, so you can spot where things are going wrong.
If you share your exact original and target URL formats, I can tweak these examples to fit your specific needs!
内容的提问来源于stack exchange,提问作者Mohsin Raza

