2013-06-29 38 views
1

我试图让mod_rewrite将所有非文件请求重定向到index.php,以便我可以处理干净URL的路由。mod_rewrite现有的目录更改地址栏中的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 /来改善此问题。但是,这会将所有网址指向尾部的斜杠。没什么大不了的,但不是我想要的。

如果,例如,/test/folder存在,我直接去,我想地址栏显示,而不是显示/test/folder//test/folder/?request=/test/folder

回答

1

好吧,持久有回报。 jerdiggity的回答提供了洞察力,这导致了进一步的实验和研究。最终,我得出结论,Apache中必须有一些内容正在重写尾部斜线。

由于可疑性,所有的重写逻辑都是准确的,但在另一个与目录相关的Apache模块mod_dir中称为DirectorySlash Directive的是添加尾部斜线。

显然,你可以简单地禁用这个指令,这是我加入到我的逻辑的顶部:

DirectorySlash Off 
RewriteEngine On 
... 
+1

不错。这里有另外一个很好的[链接](http://www.askapache.com/htaccess/mod_rewrite-variables-cheatsheet.html)来加入书签。 – jerdiggity

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文件,因为在大多数情况下,它看起来像它应该正在工作。 应该。 ;)

+0

感谢您抽出时间回复。通过添加'!-d'标志,这个逻辑产生了现有目录的目录列表,这正是我想要避免的。我想用我的index.php路由器处理现有的目录,但仍允许直接访问文件。另外,为了澄清,在我的问题中提出的代码是我的.htaccess文件的完整。 – Quantastical

+0

OK显然我错误地理解了原来的问题......我仍然不确定最终的URL是否因为你写了'如果/ test/d像地址栏显示那个(这是我以前的答案应该做的),但也许这个最新版本会帮助你走上正确的轨道。我希望..? :) – jerdiggity