如何正确重写URL以提供正确的404页面?

时间:2018-09-15 22:51:13

标签: .htaccess

我当前的.htaccess mod_rewrite配置有问题。

这是我当前的代码:

RewriteRule ^([^/]*)/([^/]*)\/$ /game.php?id=$1&title=$2 [L]
RewriteRule ^([^/]*)\/$ /index.php?page=$1 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)\/$ /category.php?cid=$1&page=$2&title=$3 [L]

上面的代码正确地重写了我的URL。但是,每当我在浏览器中键入一个不存在的目录时,例如http://www.example.com/non-existent-directory/,都会显示我的主页,而不是我已设置的404页面。

另一个要注意的是,斜杠似乎可以改变一切。如果我从网址中删除了斜杠,即http://www.example.com/non-existent-directory,则会正确显示404页。如果添加它,则会显示我的主页,而不是应该显示的404页面。

有人知道我需要做些什么来重写我的URL,但是当我键入不存在的目录时还显示404页面吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

这是ErrorDocument的方向;而一个人也可以删除斜杠:

# Rewrites
<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    # remove trailing slash
    RewriteRule ^(.*)\/(\?.*)?$ $1$2 [R=301,L]

    ...

</IfModule>

# HTTP Errors
ErrorDocument 404 /index.php?controller=frontend&method=error&id=404