Add a parameter to a wildcard 301 redirect with .htaccess in Apache

I kept typing things like “Add a parameter to a wildcard 301 redirect with .htaccess in Apache” or “add a query string to a wildcard redirect Apache”. I kept landing on pages (mostly Stack Overflow) where people were asking how to match the query string in their regex, or prevent the query string from getting copied into the redirect. I wanted the opposite. I wanted to insert a query string.

I must have just Googled this for a half-hour, but I started digging into what all the parts of the redirect mean and I figured it out. What I wanted to do was to use a wildcard redirect to send traffic from a subdomain back to the main domain, but add a parameter (or query string) to the new url.

Stack Overflow Logo

Ex: from es.domain.com/some-page/ -> domain.com/some-page/?lang=es

I just finished converting a WordPress multisite with an ‘es’ subdomain for the Spanish content, into a single site using WPML to handle the translations. In WPML, I chose to use the parameter to pass the language settings, so I needed to redirect all traffic from the ‘es’ subdomain to the main domain, but add the lang=es parameter. Make sense? Here’s my solution:

RewriteCond %{HTTP_HOST} ^es.domain.com$
RewriteRule ^(.*)$ “https\:\/\/domain.com\/$1\?lang=es” [R=301,L]

I figured out that the ‘$1’ captures “what matched” from the end of the inbound url. In my example above, this would be ‘some-page’. So it adds ‘some-page’ after the domain, but before the parameter in the RewriteRule string. I started by using CPanel’s redirect tool to create a redirect from es.domain.com to domain.com/?lang=es and checked the ‘wildcard’ box. If you don’t know, the wildcard option will try to “redirect all files within a directory to the same filename in the redirected directory.”

Screen in CPanel I was using to try to add a parameter to a wildcard 301 redirect with .htaccess in Apache

The output of that was:
RewriteRule ^(.*)$ “https\:\/\/matthewthomaslaw.com\/\?lang=es$1” [R=301,L]

I started Googling all the parts of that RewriteRule, and figured out I could just move the $1, to have the query string always be at the end.

Hope this helps someone add a parameter to a wildcard 301 redirect with .htaccess in Apache.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.