anthony_mcdougle
anthony_mcdougle

Reputation: 306

Apache: Redirect WWW to naked domain

I have an application that was written using Laravel, and it generates dynamic subdomains. Thus, I have a wildcard(*) routing mechanism. Due to several complications I'm having with SSL, I need to redirect the www.example.com routes to the naked domain (example.com), preferrably in the Apache .conf files using RewriteRules.

I've done a few searches and seen a few examples, but most of what I've seen either redirects all subdomains to the naked domain (which breaks the subdomain functionality I stated above) or does the reverse of what I'm trying to do (redirects the naked domain to www) which causes a redirect loop in many of my existing routes.

Is this something that can be done using Apache?

EDIT:

I think I fixed it. For anyone else having similar problems, I used the following rules in /etc/apache2/sites-enabled/000-default.conf:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

This redirects any URL that starts with www to its naked equivalent, which has the added benefit of stripping www from subdomains (so, for example, www.test.example.com is redirected to test.example.com which is great (although unnecessary) since www.{subdomain}.example.com is not a defined route in my app and won't work anyways.

Upvotes: 3

Views: 2862

Answers (1)

anthony_mcdougle
anthony_mcdougle

Reputation: 306

I think I fixed it. For anyone else having similar problems, I used the following rules in /etc/apache2/sites-enabled/000-default.conf:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

This redirects any URL that starts with www to its naked equivalent, which has the added benefit of stripping www from subdomains (so, for example, www.test.example.com is redirected to test.example.com which is great (although unnecessary) since www.{subdomain}.example.com is not a defined route in my app and won't work anyways.

Upvotes: 5

Related Questions