Easily Redirect Your Site to a New Domain and Add Parameters to the URL with This .htaccess Trick
2 min read
Migrating your website to a new domain? Ensuring visitors and search engines are directed to your new location is crucial for maintaining traffic and SEO rankings. By using an .htaccess file, you can implement a permanent redirect (301) that preserves your site’s integrity.
Step 1: Create or Modify the .htaccess File
- Locate your website’s root directory: This is the folder where your current site files reside (e.g.,
public_htmlorhtdocs). - Create or edit the
.htaccessfile:- If the file doesn’t exist, create a new text file named
.htaccess. - If it already exists, open it for editing.
- If the file doesn’t exist, create a new text file named
Step 2: Add Redirect Rules
Insert the following code into the .htaccess file, replacing placeholders with your new domain details:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.newdomain\.com$ [NC]
RewriteRule ^(.*)$ https://www.newdomain.com/?parameter=value [R=301,L]
Breakdown of the code
Options +FollowSymLinks: Enables symbolic link following (required for mod_rewrite).RewriteEngine On: Activates the Apache rewrite module.RewriteCond %{HTTP_HOST} !^www\.newdomain\.co.uk$ [NC]:- Checks if the requested domain is not
www.newdomain.com. [NC]makes the condition case-insensitive.
- Checks if the requested domain is not
RewriteRule ^(.*)$ https://www.newdomain.com/:?parameter=value [R=301,L]- Redirects all incoming requests (
^(.*)$) to the new domain. preserves the original URL path (e.g.,/blog/postbecomesnewdomain.com/blog/post).[R=301,L]enforces a permanent redirect and stops further processing.
- Redirects all incoming requests (
Optional Parameter
The ?parameter=value segment appends a tracking parameter to URLs (e.g., for analytics). Adjust or remove this based on your needs.
Step 3: Verify and Test
- Save the
.htaccessfile and upload it to your root directory. - Test the redirect:
- Visit
https://olddomain.com(your previous domain) in a browser. - Ensure you’re redirected to
https://www.newdomain.comwith the correct path. - Check for any broken links or missing pages.
- Visit
Why This Works
- SEO Benefits: A 301 redirect signals search engines that your site has permanently moved, preserving your search rankings.
- User Experience: Visitors are automatically routed to the new domain without disruption.
- Flexibility: The rules handle all pages and subdirectories dynamically.
- Backup First: Always keep a copy of your original
.htaccessfile before making changes.
