If you want to redirect http://www.yourdomain.com to http://www.yourdomain.com/subdirectory/, you need a specific .htaccess setup to prevent an infinite redirect loop.

Why Use .htaccess for Redirects?

The .htaccess file is a powerful configuration tool that controls redirections, URL rewrites, and access permissions on an Apache server. Setting up the correct redirect prevents your website from constantly looping back to the same URL.

.htaccess Code for Redirecting to a Subdirectory

Add the following code to the .htaccess file in the root directory of your website:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?yourdomain.com$
RewriteCond %{REQUEST_URI} !^/newfolder/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /newfolder/$1 [L]
RewriteCond %{HTTP_HOST} ^(www.)?yourdomain.com$
RewriteRule ^(/)?$ newfolder/index.php [L]

Understanding the Code

  • RewriteEngine on – Enables URL rewriting.
  • RewriteCond %{HTTP_HOST} ^(www.)?yourdomain.com$ – Ensures the rule applies only to your domain.
  • RewriteCond %{REQUEST_URI} !^/newfolder/ – Prevents an infinite redirect loop.
  • RewriteCond %{REQUEST_FILENAME} !-f – Ensures the request is not for an existing file.
  • RewriteCond %{REQUEST_FILENAME} !-d – Ensures the request is not for an existing directory.
  • RewriteRule ^(.*)$ /newfolder/$1 [L] – Redirects all requests to the subdirectory.
  • RewriteRule ^(/)?$ newfolder/index.php [L] – Ensures the homepage loads correctly.

Steps to Apply the Redirect

  1. Access your website files via FTP or cPanel File Manager.
  2. Locate the .htaccess file in your root directory.
  3. Edit the file and insert the provided code.
  4. Replace yourdomain.com with your actual domain.
  5. Replace newfolder with your actual subdirectory name.
  6. Save the changes and clear your browser cache.

Common Issues and Fixes

  • Infinite Redirect Loop: Ensure the RewriteCond %{REQUEST_URI} !^/newfolder/ condition is correctly placed.
  • 500 Internal Server Error: Double-check for syntax errors in the .htaccess file.
  • Redirect Not Working: Make sure mod_rewrite is enabled on your Apache server.

Need Help?

If you’re experiencing issues with your redirect, UnderHost’s support team is available 24/7. Contact us via @CustomerPanel for expert assistance.