RewriteRule for unknown directory

痞子三分冷 提交于 2021-01-27 13:19:22

问题


So I'm trying to get a mod_rewrite rule to redirect requests to a php-script with an .htaccess file. The thing is, I want it to work regardless of where I put the project on a webserver (the .htaccess file and the php-script are always in the same folder).

The rewrite itself is very simple. If the script and the .htacess are in the directory /path/to/project and the user visits:

/path/to/project/somestring

it should be rewritten to:

/path/to/project/index.php?t=somestring

This should work for every subdirectory at any level in the webserver. So:

If the php-script and the .htaccess files are in the root:

/somestring2

should be rewritten to:

/index.php?t=somestring2

If the php-script and the .htaccess file are in /subdirectory:

/subdirectory/somestring3

should be rewritten to:

/subdirectory/index.php?t=somestring3

So the RewriteRule should perform the same rewrite action regardless of where the project lives within the server. The string that is to become a GET-parameter can consist of those characters: [a-zA-Z0-9]. If there are other GET-parameters in the requested URL, they should be appended as well (hence the QSA flag). This is what I've tried:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*/)([a-zA-Z0-9])/? $1index.php&t=$2 [L,QSA] 

However, this results in a 404 error. How can I alter it to do what I want?


回答1:


Try :

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*/)?([A-Za-z0-9]+)/?$ /$1index.php?t=$2 [NC,L,QSA]

Note that a leading slash in rewrite pattern is not required in the RewriteRule context.



来源:https://stackoverflow.com/questions/34877605/rewriterule-for-unknown-directory

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