‹ Articles

How to Redirect to a Different Domain

To redirect all requests to a different domain name, create a .htaccess file in your app's web root directory:

public/.htaccess

with the following contents:

RewriteCond %{HTTP_HOST} =OLDDOMAIN
RewriteRule (.*) http://NEWDOMAIN/$1 [R=302,L]
You can always change the 302 to a 301 after you have confirmed your redirect is working as expected and you are ready for it to be cached by browsers. A 302 redirect is temporary and a 301 redirect is permanent. If you start with a 301 redirect and it's incorrect, your redirects will stay broken by any browsers that saw the incorrect redirect as those browsers will be caching the incorrect redirect.
Make sure the domains you are redirecting both to and from have been added to your app in ServerPilot.

For example, if you redirect from www. as shown below, both example.com and www.example.com must be added in the Domains tab of your app.

Example: Removing www. from the Domain

The following .htaccess file will redirect requests for www.example.com to the same path at the domain example.com.

RewriteCond %{HTTP_HOST} =www.example.com
RewriteRule (.*) http://example.com/$1 [R=302,L]
If you are using WordPress, be sure to place these rules above the WordPress rules.

Example: Forcing Redirection to www.

The following .htaccess file will redirect requests for example.com to the same path at the domain www.example.com.

RewriteCond %{HTTP_HOST} =example.com
RewriteRule (.*) http://www.example.com/$1 [R=302,L]
If you are using WordPress, be sure to place these rules above the WordPress rules.

Example: Redirect Everything

You can also unconditionally redirect all requests regardless of the requested domain name. This means that no content at all will be served from your app. Every single request will be redirected.

You should only use this if the domain you are redirecting to is not part of the same app, otherwise you will create a redirect loop and requests will fail with an internal server error.

To have an unconditional redirect, just exclude the RewriteCond directive in the examples above.

The following file will redirect all requests to example.com.

RewriteRule (.*) http://example.com/$1 [R=302,L]

Last updated: August 31, 2017

Still Have Questions?

Don't hesitate to contact us if you can't find the answers to your questions.