【问题标题】:Htaccess RewriteRule redirects to 404 pageHtaccess RewriteRule 重定向到 404 页面
【发布时间】:2016-06-28 04:40:13
【问题描述】:

我的基本要求是:

  1. 从所有网址中删除 .php 扩展名。
  2. 将网址从 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 扩展名,并且可以正常处理普通页面。

【问题讨论】:

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


    【解决方案1】:

    问题是你的重写规则将所有请求重写到/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]
    

    【讨论】:

    • 删除或更改 Options +Multiviews 行为 Options -Multiviews
    【解决方案2】:

    重写规则按顺序尝试。

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

    【讨论】:

    • 那么你必须查看重写日志并调试发生了什么,请参阅stackoverflow.com/a/9632952/1741542
    • 抱歉耽搁了,但我的错误日志没有显示与此相关的任何内容:(
    • 查看给出的答案以了解如何激活 rewrite 日志。调试不是一件容易的事,而且非常适合 Stackoverflow 上的简单答案。
    • XD LOL,k 让我做一些挖掘工作。 :)
    【解决方案3】:

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

    #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
    

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 2012-10-29
      • 2016-11-21
      • 2013-01-31
      • 2014-12-23
      • 2013-06-09
      • 2023-03-10
      • 2019-04-25
      相关资源
      最近更新 更多