Home > Back-end >  how to redirect www to main domain using laravel htaccess
how to redirect www to main domain using laravel htaccess

Time:09-28

I have separate subdomain in laravel. I want when some one visit: www.shawn.com it will automatically redirected to shawn.com but if anyone visit hello.shawn.com its ok to visit.

but if another one visit www.hello.shawn.com it will redirect to hello.shawn.com I have managed htaccess to access this but its not working properly.

here is my htaccess:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/$1 [L]
   RewriteEngine On 
   RewriteCond %{SERVER_PORT} 80
   RewriteCond %{HTTP_HOST} ^(www\.)?shawn\.com
   RewriteRule ^(.*)$ https://www.shawn.com/$1 [R,L]
</IfModule>

CodePudding user response:

From your description it would seem you just need to remove the www subdomain, on whatever hostname is requested. Obviously the www subdomain must currently resolve to the same place.

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/$1 [L]
   RewriteEngine On 
   RewriteCond %{SERVER_PORT} 80
   RewriteCond %{HTTP_HOST} ^(www\.)?shawn\.com
   RewriteRule ^(.*)$ https://www.shawn.com/$1 [R,L]
</IfModule>

Your current directives are in the wrong order. I assume you must have another .htaccess file in the /public subdirectory (that does the actual routing through the Laravel front-controller)? In which case, the second rule (that redirects HTTP to HTTPS www) is never processed - just as well really, since this would expose the /public subdirectory (presumably hidden from the URL) and would seem to be the opposite of what you are trying to achieve (ie. removal of www).

Try the following instead:

RewriteEngine On

# Remove "www" subdomain from any hostname
RewriteCond %{HTTP_HOST} ^www\.(. ?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

# HTTP to HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Rewrite everything to the "/public" subdirectory
RewriteRule (.*) public/$1 [L]

The <IfModule> wrapper is not required and should be removed.

No need to repeat the RewriteEngine directive.

The %1 backreference in the first rule contains the hostname, less the www. prefix, captured from the preceding condition.

NB: Test first with 302 (temporary) redirects to avoid a potential caching issue. You will likely need to clear your browser cache before testing.

CodePudding user response:

Salam. If do you need to access for subdomen www.hello.shawn.com then you must write this statement once again.

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteRule ^(.*)$ public/$1 [L]
   RewriteEngine On 
   RewriteCond %{HTTP_HOST} ^www\.hello\.shawn\.com
   RewriteRule ^(.*)$ https://hello.shawn.com/$1 [R,L]
</IfModule>
  • Related