我想为某些 HTTP 错误使用自定义页面,所以我使用 .htaccess 文件。同时我想使用URL重写,但是不行,我不知道为什么。
这是我的 .htaccess :
#Rewrite options
RewriteEngine On # Turn on the rewriting engine
#Error
RewriteRule ^error/([0-9]{3})/?$ index.php?page=error-$1 [NC,L]
#Other options
ErrorDocument 403 error/403
ErrorDocument 404 error/404
<Files .htaccess>
order allow,deny
deny from all
</Files>
IndexIgnore *
Options All -Indexes
最佳答案
ErrorDocument 指令的参数可以是字符串、内部 URI 或外部 URI。您在此处拥有的“error/404”变体被解释为字符串,因此 Apache 将其输出为硬编码错误消息。这不是我们现在想要的。
现在,如果我们在它前面加一个斜杠,“/error/404”将是一个本地重定向,但相对于 DocumentRoot 是本地的。因此,如果我们在 http://example.com/testit/.htaccess 处有 .htaccess 文件,我们要求 http://example.com/testit/something.txt , 文档 http://example.com/error/404将被加载。为避免这种情况,只需在它前面加上子目录的路径 (/testit/error/404 ),或者以其他方式使用 DocumentRoot。但是,请注意,这已经是一个软重定向:浏览器的地址栏将显示用户输入的 URI,因此无需将 ErrorDocument 的 URI 做得漂亮。只是
ErrorDocument 404 /path-to-my-folder/index.php?page=error-404
将给出一个完美的行为:当我们请求时,比如说,找不到 example.com/something.txt,地址栏将继续显示 example.com/something.txt,而 index.php 的内容?page=error-404 将被送达。
但是如果你真的想在浏览器的地址栏中显示/error/404,给 ErrorDocument 一个绝对 URI 作为参数,比如 ErrorDocument 404 http://my-server/my-path/error/404
这将强制浏览器对该文档进行硬重定向;该请求会被mod_rewrite规则捕获,并服务index.php?page=error-404的内容,而地址栏会继续显示/error/404。这种方法的缺点是您必须手动设置 404 响应 header ,并且您不知道原始请求是什么。它也可能会让机器人感到困惑,也会让访客感到困惑,因为这不是他们期望的行为。
我的建议是,让它成为一个相对链接,就像这样:
#Rewrite options
RewriteEngine On # Turn on the rewriting engine
#Other options
ErrorDocument 403 /path-to-my-subfolder/index.php?page=error-403
ErrorDocument 404 /path-to-my-subfolder/index.php?page=error-404
IndexIgnore *
Options All -Indexes
关于http - 错误文档和重写 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10740719/