Essentially, my company I work for has a site that hosts pages for several different stores. Each store has its own subdomain rule in cpanel so that users can enter a simple url from a flyer to get to the site for their local store. Recently though, Bing has started indexing one of our subdomains which causes a bit of confusion for our customers since the link appears as https://[citystate].example.com/find-us/altstate/altcity
I've looked through several files and have gotten to this point where, from what I've seen, should work but doesn't.
RewriteCond %{HTTP_HOST} ^[citystate]\.example\.com
RewriteRule ^(.*)$ https://example\.com\/$1 [L]
Can someone please assist in where i'm going wrong?
UPDATE: The piece above is working but the URL is being redirected to the index page because the page is coming up as if it doesn't exist. However, If I take the link and open it up in a separate browser window/tab it pulls up. Color me confused.
RewriteCond %{HTTP_HOST} ^[citystate]\.example\.com RewriteRule ^(.*)$ https://example\.com\/$1 [L]
This rule needs to go near the top of your .htaccess
file in order to avoid conflicts with other directives.
However, there's a couple of potential issues:
The regex snippet [citystate]
matches just a single character in the character class. [
and ]
denotes the character class. So this matches either c
, i
, t
, y
, s
, t
, a
or e
- one character only. You need to specify the word literally, without the square brackets. However, if you have many "cities" then this requires a rule for each city, you could make the regex more generic to match any city. eg. [a-z]+
(ie. 1 or more lowercase letters in the range a
to z
.)
You are missing the R
(redirect
) flag on the RewriteRule
. eg. [R,L]
or [R=301,L]
. However, since you have specified a scheme + hostname on the target URL, it will implicitly trigger a 302 (temporary) redirect - which is OK. However, in order to resolve the issue with Bing, this needs to be a 301 (permanent) redirect. But, do test with 302 (temporary) redirects first in order to avoid potential caching issues.
Minor issues:
^(.*)$
- regex is greedy by default, so the ^
and $
(start and end-of-string) anchors are superfluous.
There is no need to backslash escape literal dots and slashes in the RewriteRule
substitution since this is an "ordinary" string, not a regex.
Try the following instead:
RewriteCond %{HTTP_HOST} ^[a-z]+\.example\.com
RewriteRule (.*) https://example.com/$1 [R=301,L]
If the URL-path is not being captured properly by the $1
backreference then you can use the REQUEST_URI
server variable instead. For example:
RewriteCond %{HTTP_HOST} ^[a-z]+\.example\.com
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
Note that the REQUEST_URI
server variable contains a slash prefix, so this is omitted from the substitution string.