我的 .htaccess 中发生了很多事情,我还想添加一个重定向,但我不知道该怎么做。
所有 .php 文件都被视为 .html,如果存在同名的实际 .html 文件,则应该可以访问该文件。所有内容也通过我的主 Controller 脚本 mycontroller.php 进行路由。一切都很完美。
如果尝试使用 .php 扩展名,我想在此处添加的内容是 404 错误。这是我到目前为止所拥有的。
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.html$ $1.php [NC,L]
RewriteRule ^$ /index.php [QSA,L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+)\.php - [F,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/favicon.ico
RewriteRule ^(.*)$ mycontroller.php [L,QSA]
</IfModule>
我尝试添加从 this post 收集的内容,它有效,但它有一个不幸的副作用,使我的主页(没有在 URL 中写入/index.html)变成 404。答案的作者更新了另一行以防止这种情况发生,但它并没有似乎与我当前的脚本不兼容——所以我的主页没有写入/index.html 仍然会出现 404 错误。
可能只是我的顺序不正确,所以任何帮助将不胜感激。提前谢谢了。
最佳答案
您可以使用这样的规则:
DirectoryIndex index.php
RewriteEngine on
# block direct access to .php files
RewriteCond %{THE_REQUEST} \.php [NC]
RewriteRule \.php$ - [F,NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)\.html$ $1.php [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/favicon\.ico
RewriteRule ^ mycontroller.php [L]
关于php - 将 .php 重写为 .html 并将 .php 重定向到 .htaccess 中的 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739207/