redirect non-www to www for a specific subfolder only

1

I am trying to redirect one subfolder of my website to www if its not having www prefix. For example.

If user opens example.com/sites
it should redirect to
www.example.com/sites

Also, 

If user opens example.com/sites/whateverlink
it should redirect to  www.example.com/stores/whateverlink

For some reason, I dont want to include the main domain and other subfolders for this redirection. Please help me to write a rule for this.

Unnikrishnan

Posted 2017-07-10T07:46:54.593

Reputation: 1 193

Which server software are you using? Each one has its own method for doing so (i.e. RewriteRule in a <Location> for Apache) – Nathan.Eilisha Shiraini – 2017-07-10T07:58:05.530

apache only. I know the rule for all domains. but not subfolder – Unnikrishnan – 2017-07-10T08:18:09.827

If you want to restrict to a specific local file/folder, put the RewriteRule in a <File /path/to/file> or <Directory /path/to/directory> directive. If you want to restrict it to a specific URL, do so with a <Location /url/path/> directive. https://httpd.apache.org/docs/2.4/fr/mod/core.html#directory

– Nathan.Eilisha Shiraini – 2017-07-10T09:11:37.557

because of some reasons, I cant use the directory or location tags. Cant we write that with a rewrite rule ? – Unnikrishnan – 2017-07-10T09:28:29.700

I think you could use a RewriteCond that would only match your chosen directories. – Nathan.Eilisha Shiraini – 2017-07-10T10:04:14.433

can u plz help on this – Unnikrishnan – 2017-07-10T10:16:53.173

RewriteCond "%{HTTP_HOST}/%{REQUEST_URI}" "^example.com/sites" should restrict the next RewriteRule to example.com/sites (make sure you test it). Notice the caret in ^example.com. More info: https://httpd.apache.org/docs/current/fr/mod/mod_rewrite.html#rewritecond – Nathan.Eilisha Shiraini – 2017-07-10T11:05:47.590

thanks for the insights. I wrote it in other way. Posting as answer – Unnikrishnan – 2017-07-10T11:36:36.530

Answers

1

This rule worked perfect. Posting here as it might help someone like me.

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

Unnikrishnan

Posted 2017-07-10T07:46:54.593

Reputation: 1 193

Should work better than what I suggested ^^ don't forget to mark the answer as accepted. – Nathan.Eilisha Shiraini – 2017-07-10T11:40:53.987