Url rewriting for multiple directories

I’m trying to make site.com/category/sub-category
redirect to www.site.com/category/sub-category

This is what I have so far:
RewriteCond %{HTTP_HOST} ^site\.com$ [NC]
RewriteRule ^(.*)$ http://www.site.com/$1 [R=301,L]

It works for the second level (site.com/category) but not the third (site.com/category/sub-category).

How would you modify this to work for the third level?

Thank You E

Fortunately the Apache documentation talks about this exact situation.


Hi eruna

First, WELCOME to SitePoint!

Your code is fine as is (although you should be warned about the :kaioken: EVERYTHING :kaioken: atom).

[standard rant #1][indent]The use of “lazy regex,” specifically the :kaioken: EVERYTHING :kaioken: atom, (.*), and its close relatives, is the NUMBER ONE coding error of newbies BECAUSE it is “greedy.” Unless you provide an “exit” from your redirection, you will ALWAYS end up in a loop![/indent][/standard rant #1]

RewriteEngine on
RewriteCond %{HTTP_HOST} ^site\\.com$ [NC]
RewriteRule .? http://www.site.com%{REQUEST_URI} [R=301,L]

You could, perhaps, ensure that mod_rewrite is not in the comment mode by starting with RewriteEngine on and not using (.) to capture text already available in the {REQUEST_URI} string but you already have an escape from the loop generally created by (.) so no problem - it WILL capture everything in the path-to-file and simply repeat forcing the www.



Since the OP did provide an exit, and did not use (.*) in error, this rant seems to be unwarranted.


Did you read my post? It was provided as a warning (to the OP and others).