user2265915
user2265915

Reputation: 569

htaccess 301 redirect to root and remove query string

I am trying to redirect various pages with query strings in htaccess.

An example of the URL to be redirected is:

/item.htm?item_id=ACPEMEG465P-VE&product

I want to use a wildcard to catch anything alphanumeric after item_id*.

I want to redirect to the root domain and remove the query string. So after reviewing several guides, I have come up with:

RewriteCond %{QUERY_STRING} item_id(.*)$
RewriteRule ^item\.htm$ /? [L,R=301]

...But this doesn't seem to do anything - I'm just getting a 404. Can anyone tell me where I've gone wrong? I'm on Apache 2.4.6

Here is the htaccess:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# security measures
Header always set X-Frame-Options "sameorigin"
Header always set Referrer-Policy "same-origin"
Header always set Feature-Policy "geolocation 'self'; camera 'none'; microphone 'none'"
# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

RewriteCond %{QUERY_STRING} item_id(.*)$
RewriteRule ^item\.htm$ /? [L,R=301]

# BEGIN rlrssslReallySimpleSSL rsssl_version[3.3.4]
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
#wpmu rewritecond companydomain.com
RewriteCond %{HTTP_HOST} ^companydomain\.com [OR]
RewriteCond %{HTTP_HOST} ^www\.companydomain\.com [OR]
#end wpmu rewritecond companydomain.com
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
# END rlrssslReallySimpleSSL

I have removed sections for compression, mod_mime, mod_headers and mod_expires as they are not relevant

Upvotes: 1

Views: 268

Answers (1)

anubhava
anubhava

Reputation: 785491

Your new redirect rules comes after this rule:

RewriteRule . index.php [L]

This rule is rewriting all non-files and non-directories to /index.php and also updating REQUEST_URI variable to /index.php. Due to this your new rule:

RewriteCond %{QUERY_STRING} item_id(.*)$
RewriteRule ^item\.htm$ /? [L,R=301]

Will not execute because REQUEST_URI is not /item.htm anymore.

Once you move this rule to the top it works because REQUEST_URI is still /item.htm.

Upvotes: 1

Related Questions