【问题标题】:500 Server error instead of 404 on nested urls due to mod rewrite htaccess rule(s)由于 mod 重写 htaccess 规则,嵌套 url 上出现 500 服务器错误而不是 404
【发布时间】:2020-04-09 08:33:56
【问题描述】:

我有一个带有自定义 .htaccess 文件的网站,它处理的事情很少:

1) 它将没有“.php”扩展名的 url 视为最后有“.php”。

2) 它将http://http://www. url 重定向到https://www.

这是 .htaccess 文件:

ErrorDocument 404 /404.php

Options -MultiViews 
RewriteEngine On

## add www and turn on https in same rule
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# if not a directory and .php file is present then add .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

一切正常,但我观察到一些奇怪的行为导致 500 错误而不是 404:

1) 当您访问不存在的根级 URL(例如 https://www.example.com/skjdfhkj)时,它会按预期重定向到 404

2) 当您访问不存在的嵌套 url 例如 https://www.example.com/some-text/skjdfhkj 其中some-text 不匹配任何现有的 php 文件时,它会按预期返回 404

3) 但是,当您访问一些不存在的嵌套 url,例如 https://www.example.com/some-existing-page-name/skjdfhkj 时,其中 some-existing-page-name 匹配现有 php 文件的名称 (https://www.example.com/some-existing-page-name.php),然后它会给出一个 500 Server Error

我的问题是:我如何更新我的 htaccess 以正确返回 404 而不是 500 当有人访问不存在的嵌套 url 例如 https://www.example.com/some-existing-page-name/skjdfhkj (其中 some-existing-page-name 匹配现有 php 文件的名称(https://www.example.com/some-existing-page-name.php)) ?

我想这与 mod rewrite 有关,它将没有 .php 扩展名的 url 视为具有 .php,但不知道如何修改 htaccess 以使其正常工作:(

【问题讨论】:

    标签: php .htaccess mod-rewrite http-status-code-404


    【解决方案1】:

    尝试像这样更改最后一条规则:

    # if not a directory and .php file is present then add .php extension
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/$1.php -f
    RewriteRule ^(.+?)/?$ $1.php [L]
    

    %{REQUEST_FILENAME} 有时会使用部分匹配从文件系统中提供意外匹配。

    【讨论】:

    • 谢谢你的爱,上帝保佑你的灵魂!
    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2021-09-28
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多