How to reference the current directory from .htaccess using mod_rewrite?

旧巷老猫 提交于 2019-12-12 08:23:03

问题


I'd like to use mod_rewrite to make pretty URLs, but have a single version of the .htaccess file that can be used for any user on a server.

So far I have the standard pretty URL .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$     /index.php/$1 [L]

Ideally, I would like something similar to

RewriteRule ^(.*)$     %{URL of this file's directory}/index.php/$1 [L]

This documentation would lead me to believe that what I want is not necessary:

Note: Pattern matching in per-directory context Never forget that Pattern is applied to a complete URL in per-server configuration files. However, in per-directory configuration files, the per-directory prefix (which always is the same for a specific directory) is automatically removed for the pattern matching and automatically added after the substitution has been done. This feature is essential for many sorts of rewriting - without this, you would always have to match the parent directory which is not always possible.

I still get the wrong result, though, whether or not I put a leading / in front of the index.php on the RewriteRule.

This,

http://server/test/stream/stream

turns into

http://server/index.php/stream

not

http://server/test/index.php/stream

when the .htaccess file is in /test/.


回答1:


I was having a similar problem, but found that simply leaving off the root '/' resulted in my test web server (xampp on windows) serving a URL similar to:

http://localhost/C:/xampp/htdocs/sites/test/

Not perfect. My solution is to use a RewriteCond to extract the path from REQUEST_URI. Here's an example for removing the unwanted "index.php"s from the end of the URL:

RewriteCond %{REQUEST_URI} ^(.*)/index.php$
RewriteRule index.php %1/ [r=301,L]

Note: the percent sign in "%1/", rather than a dollar sign.

%1-%9 gets the patterns from the last matched RewriteCond, $1-$9 gets the patterns from the RewriteRule.

See: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond

Cheers :)




回答2:


Turns out that it does matter whether I put a leading / in front of index.php or not. By leaving it off, the script works correctly. I had been testing with the R flag which was using physical directories on the redirect.



来源:https://stackoverflow.com/questions/984554/how-to-reference-the-current-directory-from-htaccess-using-mod-rewrite

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!