首页 > 解决方案 > Htaccess 路由返回 404 not found

问题描述

最近,我尝试将 htaccess 用于我的语义清理器 url。这是我的代码

Options +MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

RewriteRule ^product/([0-9]+)$ home.php?id=$1 [NC]

当我导航到http://localhost/home.php?id=1它时,它会返回正确的东西,但是当我转到http://localhost/products/1它时,它会返回 404 not found 错误。

我试过这个问题:htaccess rewrite returns 404 not found and htaccess problem 404 not found but nothing works

标签: phpapache.htaccessmod-rewrite

解决方案


您可以使用以下内容:

RewriteEngine on
Options -Multiviews
#rewrite /filename to /filename.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)/?$ $1.php [L]
# /product/123 to home.php?id=123
RewriteRule ^product/([0-9]+)$ home.php?id=$1 [NC]

当请求的 URI 是/product/1因为您的第一条规则将其重写到未知位置时,您的规则会返回 404 /product/1.php。我在第一条规则中添加了一个条件,以便它检查请求是否实际上是针对.php文件的。


推荐阅读