Jenski
Jenski

Reputation: 1468

How to create a 301 redirect based on a query string within a subfolder?

I have a .htaccess file in the root of a website:

/var/www/mywebsite/htdocs/.htacess

and I have some files in

/var/www/mywebsite/htdocs/folder/

which are currently generated by index.php?pc=1234

I want to redirect the numbers in the query string variable to static html pages within that folder. I can achieve this in the .htacess file in the root of the website by:

RewriteRule ^folder/\?pc=1 /folder/filename.html [R=301,L]

However as there are a few of these files, it would be useful if I could create a .htaccess file in:

/var/www/mywebsite/htdocs/folder/.htaccess

My question is: How do I capture the querystring and redirect accordingly from this folder?

Upvotes: 0

Views: 1544

Answers (3)

Jenski
Jenski

Reputation: 1468

Thanks Residuum and Nerdling. You guys gave me some ideas.

This was what I ended up with. The following in /var/www/mywebsite/htdocs/folder/.htaccess

RewriteEngine On
RewriteBase /folder
RewriteCond %{QUERY_STRING} pc=1
RewriteRule ^$ filename.html? [R=301,L]

If I didn't include the RewriteBase the URL would appear as:

www.mywebsite.com/var/www/mywebsite/htdocs/folder/

But with it appeared properly as:

www.mywebsite.com/folder/filename.html

I also had to create a rewrite rule which captured a blank filename i.e. " ^$ " then delcare the filename i wanted pc=1 to go to.

Thanks again Residuum, Nerdling

Upvotes: 2

Residuum
Residuum

Reputation: 12064

In subfolders, only use the relative URL:

RewriteEngine On
RewriteBase /folder
RewriteRule ^\?pc=1 filename.html [R=301,L]
RewriteRule ^\?pc=2 someotherfilename.html [R=301,L]

Or Similar to using RewriteCond as Nerdling said, but using skip for your rewrite rules, like this:

# this will skip the two line for anything not matching ^folder/\?pc=
RewriteRule !^folder/\?pc= - [S=2] 
RewriteRule ^folder/\?pc=1 /folder/filename.html [R=301,L]
RewriteRule ^folder/\?pc=2 /folder/someotherfilename.html [R=301,L]
# anything else will be interpreted again

Or use the rule for terminating interpretation for anything else:

RewriteRule !^folder/\?pc= - [L] 
RewriteRule ^folder/\?pc=1 /folder/filename.html [R=301,L]
RewriteRule ^folder/\?pc=2 /folder/someotherfilename.html [R=301,L]

Upvotes: 1

Jeremy L
Jeremy L

Reputation: 7797

Before the RewriteRule for 301, place something like this:

RewriteCond %{QUERY_STRING} MATCH

where MATCH is whatever you want to match. You can use multiple ones with the [OR] block at the end.

You can find more information at Apache's website.

Upvotes: 2

Related Questions