How htaccess 301 redirect pages with question mark in url

I am trying to redirect multiple pages that have all the question marks in the URL.

I really want to redirect:

www.example.com/?attachment_id=456 to www.example.com

      

There are also many pages with id # honors.

I have tried several things in htaccess with no luck.

Any ideas?

This is what I tried:

RewriteCond %{QUERY_STRING} ^attachment_id=[0-9]
RewriteRule ^/$ http://www.example.com/? [L,NC,R=301]

      

+3


source to share


2 answers


Why can't you do this? This code should redirect url like thiswww.example.com/?attachment_id=456

RewriteCond %{QUERY_STRING} ^attachment_id=[0-9]+
RewriteRule ^/?$ http://www.example.com/? [L,NC,R=301]

      



I made the option /

optional so it can be used in Apache config or .htaccess. Also I saved ?

which you have in the redirect at the end of the RewriteRule to remove the query lines on the redirect.

+5


source


Your approach is close to perfect, only some minor fixes:

RewriteEngine on
RewriteCond %{QUERY_STRING} attachment_id=[0-9]+
RewriteRule ^/$ http://www.example.com/ [L,R=301]

      

The above version is for host config. please note that you need to restart the http server after making changes to the host configuration for them to be effective. For debugging, refer to the http servers error log file, especially during restart.

If you have to rely on style files .htaccess

, then the syntax for the rule itself should, unfortunately, be slightly different:



RewriteEngine on
RewriteCond %{QUERY_STRING} attachment_id=[0-9]+
RewriteRule ^$ http://www.example.com/ [L,R=301]

      

Such a file must be located in the main document root folder of the site. also the interpretation of such files must be enabled in the host configuration using the option AllowOverride

.

In general, you should always prefer the host configuration for such rules over style files .htaccess

, but you need administrative access to do this. .htaccess

style files are known to be error prone, difficult to debug, and really slow down the server.

+4


source







All Articles