Home > Mobile >  .htaccess redirects too many times
.htaccess redirects too many times

Time:12-10

I have written a .htaccess for the subdomain but it redirects too many times.

my complete code looks like

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ http://subdomain/$1 [R,L]
    
RewriteEngine On      

RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L]
  
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^404/?$ /404.php [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^ http://subdomain/404 [L,R]

CodePudding user response:

The issue most likely is the topmost redirection. It implements a redirection loop. Also it is unclear what it is actually meant to achieve ... What is "subdomain" here? A hostname / subdomain name? So something like http://sub.example.com/$1?

Assuming that all "sub domains" you served by the same http server you'd need to add an additional condition to break that look:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HOST_NAME} !^sub\.example\.com$ 
RewriteRule ^(.*)$ http://sub.example.com/$1 [R,L]

That could also be simplified to this:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HOST_NAME} !^sub\.example\.com$ 
RewriteRule ^ http://sub.example.com%{REQUEST_URI} [R,L]

Also consider using the encrypted https protocol, it actually is the standard these days.

CodePudding user response:

RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ http://subdomain/$1 [R,L]

You've not actually stated what you are trying to do. However, the only reason to check the SERVER_PORT for port 80 like this is if you are redirecting to HTTPS (port 443). But you are redirecting to HTTP (port 80) - so this will naturally result in a redirect loop.

You need to change http to https in the substitution string. For example:

RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://subdomain/$1 [R=301,L]

(Ultimately, this should be a 301 permanent redirect, once you have confirmed it works as intended.)

OR, remove these directives entirely.


RewriteRule ^ http://subdomain/404 [L,R]

And change to https in the last rule. (But the last two rules are rather silly.)

  • Related