HTAcess 301 Redirect URL Parameter that has a Wildcard?

1.7k views Asked by At

I have taken over a website and have rewritten the gallery facility to use the Fancy light-box plugin instead of separate pages for each image, 42 pages in total, i.e gallery now only consists of a single webpage now.

Therefore, I added lines to the HTAcess file for all the relevant 301s, 42 times :( :

RewriteCond %{HTTP_HOST}  ^www\.mydomain\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^view=14$ [NC]
RewriteRule ^viewGallery\.php$ http://www.mydomain.com/gallery/?view=14 [R=301,NE,NC,L]

Is there a way to use a wildcard to capture the gallery number, in this case 14, and shorten the section to just single entry in the HTAccess file?

Thank you for any advice.

1

There are 1 answers

1
Jon Lin On BEST ANSWER

Try:

RewriteCond %{HTTP_HOST}  ^www\.mydomain\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^view=([0-9]+)$ [NC]
RewriteRule ^viewGallery\.php$ http://www.mydomain.com/gallery/?view=%1 [R=301,NE,NC,L]

This is essentially what you have except you change the regex for the query string to capture the ID, then you can backreference it using %1 in the rule's target.

But, an easier way to do it is:

RewriteCond %{HTTP_HOST}  ^www\.mydomain\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^view=([0-9]+)$ [NC]
RewriteRule ^viewGallery\.php$ http://www.mydomain.com/gallery/ [R=301,NE,NC,L]

Simply remove the ?view=%1 part altogether. The rewrite engine will automatically append the query string to the end as long as you don't have a ? in the target.