web-tip.top
WTT

Useful Apache redirects (.htaccess)

19.05.2024

Some useful Apache redirects (.htaccess).

# 301 redirect all pages from old domain to new one
RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com$
RewriteRule ^(.*)$ https://www.newdomain.com/$1 [R=301,L]

# 301 redirect from www to non www
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# 301 redirect from non www to www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

# 301 redirect from http://www, https://www and http:// to https://
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

# 301 redirect from http to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R=301,L]

# Remove index.php from url
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

# Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^(.+)/$
RewriteRule ^(.+)/$ /$1 [R=301,L]

# Add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpg|png|jpeg|css|js|xml)$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]

# Remove multiple slashes
RewriteCond %{THE_REQUEST} \s[^?]*//
RewriteRule ^.*$ /$0 [R=301,L,NE]

# Remove last empty ? from url, ex. https://site.ru/?
RewriteCond %{THE_REQUEST} ^[^\s]+\s+[^?]*?\?
RewriteCond %{QUERY_STRING} =""
RewriteRule .? %{REQUEST_URI}? [R=301,L]

# 301 redirect from http:// to http://www and from https://www to https://
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} (.+)$
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Redirect single page
Redirect 301 /old-url /new-url

# Redirect single page to home page
RewriteRule ^someurl/?$ / [R=301,L]