Apache 2下.htaccess URL重写配置正确性及优化方案咨询
Fixing .htaccess to Remove index.php from Your URLs
First, let's break down why your current setup isn't working. Using an absolute URL (http://localhost/test/boutique/index.php/$1) in the RewriteRule triggers an external redirect instead of the internal rewrite you need, which is likely the main issue. We also need to scope the rule properly to your /test/boutique/ directory to avoid unintended behavior elsewhere.
Prerequisites to Check First
Before tweaking the .htaccess code, confirm these two critical Apache settings are in place:
- mod_rewrite is enabled: If you have server shell access, run
a2enmod rewriteand restart Apache. For shared hosting, check your host's documentation or support to verify it’s turned on. - AllowOverride is configured correctly: In your Apache main config (or virtual host file), ensure the directory block for your
/test/boutique/folder usesAllowOverride All(notNone). This lets Apache read and process your .htaccess file. Example:
Restart Apache after making this change.<Directory "/var/www/html/test/boutique"> AllowOverride All Require all granted </Directory>
Correct .htaccess Configuration
Place this code directly in the .htaccess file inside your /test/boutique/ folder:
RewriteEngine On # Skip rewrites for actual files or directories RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Internally rewrite the request to index.php with the path appended RewriteRule ^(.*)$ index.php/$1 [L]
What Each Line Does
RewriteEngine On: Enables Apache's rewrite module to process the rules below.- The two
RewriteCondlines: Ensure we only rewrite requests that don’t point to an existing file (like images or CSS) or directory. This prevents breaking your static resources. RewriteRule ^(.*)$ index.php/$1 [L]: Captures everything after/test/boutique/(stored as$1) and appends it toindex.phpinternally. The[L]flag tells Apache this is the final rule to apply for the current request.
Testing the Setup
After saving the config, test your friendly URLs:
localhost/test/boutique/language,enshould internally map tolocalhost/test/boutique/index.php/language,enlocalhost/test/boutique/Products/Description/products_id,1should map tolocalhost/test/boutique/index.php/Products/Description/products_id,1
If you still run into issues, try these debugging tips:
- Temporarily enable Apache's rewrite log to see what’s happening. Add these lines to your Apache main config (not .htaccess) and restart:
Check your Apache error log to trace how the rules are being applied.LogLevel alert rewrite:trace3 - Make sure there are no conflicting rewrite rules in higher-level .htaccess files (like
/test/or the root directory). - Clear your browser cache before testing—old redirects can get cached and interfere with new rules.
内容的提问来源于stack exchange,提问作者Zigoto
相关产品推荐
相关产品推荐

