【问题标题】:mod_rewrite existing directory changes URL in address barmod_rewrite 现有目录更改地址栏中的 URL
【发布时间】:2013-06-29 03:38:55
【问题描述】:

我正在尝试让 mod_rewrite 将所有不是文件的请求重定向到 index.php,以便我可以处理干净 URL 的路由。

<IfModule mod_rewrite.c>  
    RewriteEngine On

    # Route requests to index.php for processing
    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteRule ^(.+)$ index.php?request=$1 [QSA,L]
</IfModule>

由于某种原因,当我访问一个没有尾部斜杠的现有目录时,地址栏会重新包含一个尾部斜杠和查询字符串,这不是很干净。

我可以通过将 RewriteRule 更改为 ^(.+)/$ 并添加 RewriteBase / 来改进这一点。但是,这会将所有 URL 指向一个带有尾部斜杠的 URL。没什么大不了的,但不是我想要的。

例如,如果 /test/folder 存在并且我直接转到该地址栏,我希望地址栏显示它,而不是显示 /test/folder//test/folder/?request=/test/folder

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    我会试试看:

    DirectoryIndex index.php
    <IfModule mod_rewrite.c>  
        RewriteEngine On
        # I tested this inside a subdir named "stack", so I had to uncomment the next line 
        #RewriteBase /stack
    
        # Route requests to index.php for processing
    
        # Check if the request is NOT for a file:
        RewriteCond %{REQUEST_FILENAME} !-f
    
        # Check if the request IS for an existing directory:
        RewriteCond %{REQUEST_FILENAME} -d
    
        # If all criteria are met, send everything to index.php as a GET request whose
        # key is "request" and whose value is the entire requested URI, including any
        # original GET query strings by adding QSA (remove QSA if you don't want the 
        # Query String Appended): 
        RewriteRule .* index.php?request=%{REQUEST_URI} [R,L,QSA]
    </IfModule>
    

    如果这不起作用,请让我知道您的 .htaccess 文件中还有什么,因为在大多数情况下,它看起来应该可以正常工作。 应该。 ;)

    【讨论】:

    • 感谢您抽出宝贵时间回复。通过添加!-d 标志,此逻辑会为现有目录生成目录列表,这是我试图避免的。我想用我的 index.php 路由器处理现有目录,但仍然允许直接访问文件。另外,澄清一下,我的问题中提供的代码是我的 .htaccess 文件的全部内容。
    • 好吧,显然我误解了最初的问题......我仍然不确定你是否希望最终 URL 看起来像,因为你写了If, for example, /test/folder exists and I go to that directly, I'd like the address bar to display that(这是我之前的回答应该做的),但也许这个最新版本将帮助您走上正轨。我希望..? :)
    【解决方案2】:

    嗯,坚持是有回报的。 jerdiggity 的回答提供了洞察力,这导致了进一步的实验和研究。最终,我得出的结论是,Apache 中肯定有一些东西正在重写尾部斜杠。

    正如 jerdiggity 所怀疑的那样,所有的 Rewrite 逻辑都是准确的,但是在另一个与目录相关的 Apache 模块 mod_dir 中称为 DirectorySlash Directive 的东西正在添加尾部斜杠。

    显然,您可以简单地禁用这个指令,我将它添加到我的逻辑顶部:

    DirectorySlash Off
    RewriteEngine On
    ...
    

    【讨论】:

    • 不错。这是另一个很好的 link 书签。
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2014-03-29
    • 2015-03-06
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多