.htaccess多索引文件规则中RewriteCond不生效问题
Fixing .htaccess Rules for Targeted 404 and Proper Path Handling
Key Issues in Current Code
- Missing coverage for
/index.php: Your first rule only blocks/and/index.html, but you need to include/index.phpto meet your requirement. - Incorrect rewrites for
some-path: The rule rewritingsome-path/...to/...sends requests to the root directory, which either hits the 404 block or points to non-existent files, causing allsome-pathrequests to fail. - Misplaced
.htmlrewrite target: The rule for rewriting paths likesome-path/aboutto.htmltargets the root instead of thesome-pathdirectory.
Corrected .htaccess Code
RewriteEngine On # Block root "/" and "/index.php" with 404 RewriteCond %{THE_REQUEST} ^GET\ /(index\.php)?\ HTTP/ RewriteRule ^index\.php?$ - [L,R=404] # Block direct access to "/some-path/" (no trailing file) with 403 RewriteCond %{REQUEST_URI} ^/some-path/?$ RewriteRule ^ - [L,R=403] # Rewrite clean paths in some-path to their corresponding .html files (within some-path) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^some-path/([^/.]+)$ /some-path/$1.html [L]
Explanation of Changes
- Root 404 Block: Using
%{THE_REQUEST}ensures we catch both direct requests for/and/index.php, avoiding issues with internal server rewrites (like Apache automatically loadingindex.phpfor/). - Removed Harmful Rewrite: The rule that moved
some-pathfiles to the root is removed—this allows Apache to serve files like/some-path/index.phpdirectly from their correct directory. - Fixed
.htmlRewrite: Now rewrites paths like/some-path/aboutto/some-path/about.html, ensuring the file is looked up in thesome-pathdirectory instead of the root.
Testing
- Access
http://domain/orhttp://domain/index.php: Returns 404. - Access
http://domain/some-path/index.php: Serves the file from thesome-pathdirectory. - Access
http://domain/some-path/about: Rewrites to/some-path/about.html(if the file exists). - Access
http://domain/some-path/: Returns 403.
内容的提问来源于stack exchange,提问作者Kirill Zaytsev
相关产品推荐
相关产品推荐

