开发者

htaccess rewrite subdirectory name to querystring param

开发者 https://www.devze.com 2023-02-06 13:55 出处:网络
I have some specific needs for a certain directory of my website.I need to change /thisDirectory/subDirectory

I have some specific needs for a certain directory of my website. I need to change

/thisDirectory/subDirectory

to come through as

/thisDirectory?param=subDirectory

I'm开发者_Python百科 having issues successfully creating an htaccess file that will do that. I've tried SEVERAL different things, but I think this is the closest:

RewriteEngine On
RewriteRule ^/directory/(.*)\??(.*)$ /directory/?page=$1&$2

I've been facing all kinds of 500 Server Errors, infinite redirect loops, etc etc. Any help would be much appreciated, thanks!


I’m surprised that this does work at all in a per-directory context as you would have to strip the per-directory path prefix from the pattern:

When using the rewrite engine in .htaccess files the per-directory prefix (which always is the same for a specific directory) is automatically removed for the RewriteRule pattern matching and automatically added after any relative (not starting with a slash or protocol name) substitution encounters the end of a rule set.

In case of the document root directory that would be the leading / and the rule would look like this:

RewriteRule ^directory/(.*)\??(.*)$ /directory/?page=$1&$2

But besides that, RewriteRule can only check the URI path and not the query; you need RewriteCond to do that. So try this:

RewriteRule ^directory/(.+)$ /directory/?page=$1 [QSA]

Here the .+ instead of .* should avoid an infinite recursion as .* matches everything, even an empty string (that would be the case for the empty path segment after /directory/). And the QSA flag is to automatically append the requested URI query to the new one.


After much frustration... I think the issue was trying to do a rewrite to the same "directory" (although I thought the [L] would take care of it not looping... but that didn't seem to be the case). I changed the name of the directory it was rewriting to and it seems to work...

RewriteBase /my/base/rewrite/
RewriteRule ^directory/(.*)$ newDirectory/?page=$1 [L]
0

精彩评论

暂无评论...
验证码 换一张
取 消