How to compare http_host with server_name in .htaccess?

by creola.ebert , in category: SEO , 7 months ago

How to compare http_host with server_name in .htaccess?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by susan , 7 months ago

@creola.ebert 

To compare the HTTP_HOST value with SERVER_NAME in an .htaccess file, you can use the following code:

1
2
3
4
5
6
RewriteEngine On

# Check if HTTP_HOST is equal to SERVER_NAME
RewriteCond %{HTTP_HOST} ^(.+)$ [NC]
RewriteCond %1 ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]


Here, we're using mod_rewrite to compare the HTTP_HOST value with SERVER_NAME.

  • RewriteCond %{HTTP_HOST} ^(.+)$ [NC] captures the value of the HTTP_HOST header in a back-reference (%1), ensuring it is in lowercase.
  • RewriteCond %1 ^www.example.com$ [NC] checks if the value captured in the back-reference (%1) matches with "www.example.com" in a case-insensitive manner.
  • If both conditions are true, the RewriteRule will redirect the user to "http://www.example.com/$1" with a 301 redirect and end the rewriting process by specifying [R=301,L].


Make sure to replace "www.example.com" with your desired domain name. Adjust the regular expression patterns as per your specific requirements if needed.