首页 文章

Htaccess RewriteRule重定向到404页面

提问于
浏览
0

我的基本要求是:

  • 从所有网址中删除 .php 个扩展名 .

  • 将网址从 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

The problem I am facing is that, RewriteRule fails. I mean, when I try to access softwares/page_name/sub_category, its throwing a 404 error.

注意:它正确删除.php扩展名并正常页面正常工作 .

3 回答

  • 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]
    
  • 0

    按顺序尝试重写规则 .

    这意味着 softwares/page_name/sub_category 被第一个规则重写为 /unsync/softwares/page_name/sub_category.php ,找不到 . 因此,您会收到404 Not found错误 .

  • 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
    

相关问题