apache.htaccessmod-rewritehttp-redirectpretty-urls

htaccess pretty url and force www


I've been using following code to achieve pretty urls:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ index.php?p=$1 [L]

And it is working fine.

However, I also need to force my domain to redirect to www while keeping pretty urls.

I've read through some threads that ask for redirection to www, but I am unable to implement it together with pretty url (domain.com -> www.domain.com, domain.com/news -> www.domain.com/news respectively).

Can anyone help me achieve this?


Solution

  • Have www redirect rule before rewrite rule you already have:

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/.]+)/?$ index.php?p=$1 [L,QSA]