This isn’t ideal for SEO reasons — but I have little choice:
I’m trying to redirect 50 URLs, one for each of our United Sates, like so, from:
http://www.example.com/411/states/Alabama.html
to
https://example.com/wp/myfolder?search_field=state&value=AL
Beyond forwarding to a different URL, there are three things I also need to accomplish:
- Add the query string
- Force the use of
https
regardless of whether or nothttps
orhttp
was contained in the original URL - It shouldn’t matter whether a visitor enters the "www" or not.
There are plenty of online examples showing the opposite (URL with query > URL without query) – but I couldn’t find one going this direction.
I’ve tried quite a few combinations, most recently:
RewriteCond %{HTTP_HOST} ^.mydomain.com$
RewriteRule ^411/states/Alabama.html$ https://example.com/wp/myfolder?search_field=state&value=AL [L,R=301]
2
Answers
If you're having the same problem, here's what worked for me:
This is basically correct, you just need to remove the
RewriteCond
directive (it will never match, but would not seem to be required anyway). The literal?
in the substitution string does not need to be backslash-escaped (but its not a problem either).There is no special treatment required when redirecting from a URL without a query string (or one where you are not concerned about the query string) to a URL with a query string. Just state the target URL as written.
However, for this specific problem of redirecting all 50 states… you could instead use just a single rule and use 50 conditions (
RewriteCond
directives), one for each state, to look-up the "state code". This would help to avoid repetition and would be more efficient since there is only one rule to process, not 50.(I’ve assumed the
411
part of the URL is just an arbitrary numeric code, different for each URL and not required for a successful match.)For example:
The
$1
backreference contains the "state name" as captured from the URL-path. The(..)
in the CondPattern captures the corresponding 2 character "state code" from the TestString.The
%1
backreference contains the matched "state code". Specifically, this contains the first captured group from the last matched CondPattern. All the conditions areOR
‘d; only one can match.Note that the last condition (
RewriteCond
directive) does not have anOR
flag.(This doesn’t specifically check for an empty query string, as that does not seem to be necessary.)