Search code examples
.htaccessapache2hosting

How To Redirect www to Non-www with path url complete in apache2


All paths with www (www.example.com/posts/categories) redirect to the home page. How can i redirect from .htaccess and keep the full path?

https://www.example.com/posts/categories to https://example.com/posts/categories

current configuration:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

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

</IfModule>

Solution

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

    You've put this rule in the wrong place. It needs to go at the start, immediately after the RewriteEngine directive. By placing it at the end, after the rewrite to index.php, any request for the www subdomain will be redirected to index.php (during the second round of processing).

    As a general rule, external redirects should always go before internal rewrites.

    You should also consider implementing an HTTP to HTTPS redirect.