【问题标题】:Rewriting .php to .html and redirecting .php to a 404 in .htaccess将 .php 重写为 .html 并将 .php 重定向到 .htaccess 中的 404
【发布时间】:2015-10-22 17:19:24
【问题描述】:

我的 .htaccess 中有很多事情要做,我还想添加一个重定向,但我不知道该怎么做。

所有 .php 文件都被视为 .html,如果存在同名的实际 .html 文件,则应该可以访问该文件。一切都通过我的主控制器脚本 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 错误。

可能只是我没有正确的订单,因此我们将不胜感激。提前谢谢了。

【问题讨论】:

    标签: php regex apache .htaccess mod-rewrite


    【解决方案1】:

    你可以使用这样的规则:

    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] 
    

    【讨论】:

    • 不确定你是否会看到这个,但有没有办法让它重定向到我的 404 文件?当我输入“ErrorDocument 404 /404.html”时,.php 扩展名会重定向到错误,而不会转到我的 404 页面。
    • 您可以使用ErrorDocument 403 /404.html,您的自定义页面将显示出来。
    猜你喜欢
    • 2017-05-31
    • 2015-10-22
    • 2012-12-01
    • 2013-09-12
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多