Htaccess rewrite subdirectory name for querystring param parameter

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

/thisDirectory/subDirectory 

to get through

 /thisDirectory?param=subDirectory 

I am having problems creating an htaccess file that will do this. I tried a few different things, but I think this is the closest:

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

I came across all kinds of 500 server errors, endless redirect cycles, etc. Any help would be greatly appreciated, thanks!

+4
source share
2 answers

I am surprised that this generally works in context for each directory, since you would need to remove the path prefix for each directory from the template:

When using the rewrite mechanism in .htaccess files, the prefix for each directory (which is always the same for a specific directory) is automatically deleted to match the RewriteRule pattern and automatically added after any relative (not starting with a slash or protocol name) substitution meets the end of the ruleset .

In the case of the document root, which will be the leading / , the rule will look like this:

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

But also, the RewriteRule can only check the URI path, not the request; you need a RewriteCond for this. So try the following:

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

Here .+ Instead of .* Infinite recursion should be avoided, since .* Matches everyone, even an empty line (this would be the case for an empty path segment after /directory/ ). And the QSA flag is to automatically add the requested URI request to the new one.

+3
source

After much disappointment ... I think the problem was to rewrite to the same "directory" (although I thought that [L] would take care of this without looping ... but it did not seem so). I changed the name of the directory to which it corresponded, and it seems to work ...

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

Source: https://habr.com/ru/post/1337073/


All Articles