htaccess collection – mod_rewrite rules

Below are common htaccess redirects for wordpress.

#Block a certain domain from being accessed
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.somedomainexample.com$
RewriteRule .* - [F]

 

PHP Alternative for same:

if($_SERVER['HTTP_HOST'] == 'www.gooddomain1.com' || $_SERVER['HTTP_HOST'] == 'gooddomain1.com'){
	//run some codes
	1;
}else{
	exit;
}

Redirection www and non www:

By default, wordpress + plugins handle these automatically. But relying on wordpress is slow. Htaccess will save you a lot of load time (and cpu processing power), so you can handle many visitors at once. From experience, each redirect may take up to 1.25 seconds even on a fast server with minimal load. So this really does make a difference.

# http://domain.com -> https://www.domain.com/

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} !=""
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

 

# http://domain.com -> https://domain.com/

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
#http://domain.com -> https://domain.com/en/
#https://domain.com -> https://domain.com/en/
#this is great for WPML where default language is set as directory. You can skip 2 wordpress redirects with this rule

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/en/ [R=301,L]
</IfModule>

 

Helpful Link:

rewrite rule tester: https://htaccess.madewithlove.be/