Htaccess RewriteRule重定向到404页面

时间:2016-06-27 06:04:05

标签: php apache .htaccess mod-rewrite url-rewriting

我的基本要求是:

  1. 从所有网址中删除 .php 扩展程序。
  2. http://localhost/unsync/softwares/page_name/sub_category/ 的网址重写为 http://localhost/unsync/softwares.php?p=page_name&sub_cat=sub_category
  3. 以下是我的 .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扩展名,并且正常页面正常工作。

3 个答案:

答案 0 :(得分:0)

问题是你的重写规则重写了对/unsync/request.php的所有请求,你必须在重写请求之前检查php文件的存在,

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

或者您可以简单地在模式中排除斜杠,以便它不会与您的其他规则冲突

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

答案 1 :(得分:0)

按顺序尝试重写规则。

这意味着softwares/page_name/sub_category会被/unsync/softwares/page_name/sub_category.php的第一条规则重写,但未找到。$(document).ready -> ... 因此,您会收到404 Not found错误。

答案 2 :(得分:0)

经过一整天的研究,我终于可以自行解决我的问题了(如果有人遇到类似的问题正在寻找解决方案):

#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
相关问题