Haccess RewriteRule重定向到404页


Htaccess RewriteRule redirects to 404 page

我的基本要求是:

  1. 从所有url中删除.php扩展
  2. 将URL从http://localhost/unsync/softwares/page_name/sub_category/重写为http://localhost/unsync/softwares.php?p=page_name&sub_cat=sub_category

以下是我的.htaccess代码:

# Do not remove this line, otherwise mod_rewrite rules will stop working
Options +MultiViews
RewriteEngine On
RewriteBase /
#Prevent viewing of .htaccess file
<Files .htaccess>
order allow,deny
deny from all
</Files>
#Prevent directory listings
Options All -Indexes
#Error Documents
ErrorDocument 400 /unsync/error.php?code=400
ErrorDocument 401 /unsync/error.php?code=401
ErrorDocument 402 /unsync/error.php?code=402
ErrorDocument 403 /unsync/error.php?code=403
ErrorDocument 404 /unsync/error.php?code=404
ErrorDocument 500 /unsync/error.php?code=500
ErrorDocument 503 /unsync/error.php?code=503
#Remove extensions
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^'.]+)$ /unsync/$1.php [NC,L]
RewriteRule softwares/(.*)/(.*)/$ /softwares.php?p=$1&sub_cat=$2 [L]
DirectoryIndex index.php

我面临的问题是,RewriteRule失败。我的意思是,当我尝试访问softwares/page_name/sub_category时,它会抛出404错误

注意:它正确地删除了.php扩展,并且可以正常使用普通页面。

问题是,您的重写规则将所有请求重写到/unc/request.php,在重写请求之前,您必须检查php文件的存在,

    #Remove extensions
    RewriteCond %{DOCUMENT_ROOT}/unsync/$1.php -f
    RewriteRule ^([^'.]+)$ /unsync/$1.php [NC,L]

或者你可以简单地排除模式中的斜杠,这样它就不会与你的其他规则冲突

    RewriteRule ^([^'/.]+)$ /unsync/$1.php [NC,L]

按顺序尝试重写规则。

这意味着softwares/page_name/sub_category被第一条规则重写为未找到的/unsync/softwares/page_name/sub_category.php。因此,您会得到一个404未找到错误。

经过一整天的研究,我终于可以自己解决我的问题了,如下所示(如果有人面临类似的问题正在寻找解决方案(:

#If both p and sub_cat are issued
RewriteRule ^softwares/(.+)/(.*)$ /unsync/softwares.php?p=$1&sub_cat=$2 [NC,L]
#If only p is issued
RewriteRule ^softwares/(.*)$ /unsync/softwares.php?p=$1 [NC,L]
#Remove extensions
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^'.]+)$ /unsync/$1.php [NC,L]
DirectoryIndex index.php