Common 301 Redirect Htaccess Rules

Here are some common 301 redirect rules that can be added to an .htaccess file: Redirect a single page: Redirect 301 /old-page.html http://www.example.com/new-page.html

This rule redirects the old page "/old-page.html" to the new page "http://www.example.com/new-page.html". Redirect an entire domain: Redirect 301 / http://www.newdomain.com/ This rule redirects all pages on the old domain to the home page of the new domain. Redirect a directory: RedirectMatch 301 ^/old-directory/(.*)$ http://www.example.com/new-directory/$1

This rule redirects all pages in the old directory "/old-directory/" to the corresponding pages in the new directory "/new-directory/". The "$1" is a backreference to the part of the URL that matches the "(.*)" pattern. Redirect all non-www requests to www: RewriteEngine On RewriteCond %{HTTP_HOST} !^www\.example\.com$ RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

This rule redirects all requests that do not begin with "www" to the corresponding URL with "www". For example, "example.com" would be redirected to "www.example.com". Redirect all requests to HTTPS: RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This rule redirects all requests to the corresponding URL with "https" instead of "http".


Redirect from an old domain to a new domain that includes the full path and query string


Options +FollowSymLinks

RewriteEngine On

RewriteRule ^(.*) http://www.newdomain.com%{REQUEST_URI} [R=302,NC]



RewriteEngine On: This directive enables the Apache mod_rewrite module, which is required for URL rewriting.

RewriteRule: This is the main directive for URL rewriting. It specifies the pattern to match in the requested URL and the replacement URL to use if the pattern is matched.

^(.): This is the pattern to match in the requested URL. The caret (^) indicates the start of the URL and the dot-star (.) matches any character zero or more times. This effectively matches the entire URL path and query string.

http://www.newdomain.com%{REQUEST_URI}: This is the replacement URL to use if the pattern is matched. It consists of the new domain name, followed by the requested URI (path and query string), which is obtained using the %{REQUEST_URI} variable.

[R=302,NC]: This specifies the rewrite rule flags, which modify the behavior of the rule. The R=302 flag indicates a temporary redirect (HTTP status code 302), which tells clients and search engines that the redirect is temporary and the original URL may be used again in the future. The NC flag makes the pattern match case-insensitive.

Overall, this rule will redirect all requests to the new domain without changing the path and query string, using a temporary redirect.





Comments

Popular posts from this blog

Shell script to find out aliases and their expiration in cacerts

shell script to scp multiple file to multiple destinations

How to resolve port conflict in websphere