Amrinder Singh
Amrinder Singh

Reputation: 5492

How to restrict Http redirection to Https for specific directory?

I am redirecting users from Http to Https, it is working fine, but client's requirement is to skip one directory for this.

For example: the user should not redirect to https if he access the following url: www.example.com/ads, but it should redirect if he access any other URL.

Here is the code I am using currently:

<VirtualHost *:80>
   ServerName example.com
   ServerAlias www.example.com
   RewriteEngine on
   RewriteRule ^/(.*)$ https://www.example.com/$1 [QSA,L,R=301]
</VirtualHost>

Upvotes: 0

Views: 126

Answers (3)

anubhava
anubhava

Reputation: 785128

Assuming you don't have a .htaccess in ads/ sub-directory.

Have your exclusion rule like this using THE_REQUEST variable:

<VirtualHost *:80>
   ServerName example.com
   ServerAlias www.example.com

   RewriteEngine on

   RewriteCond %{THE_REQUEST} !\s/+ads [NC]
   RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R=301]
</VirtualHost>

Don't forget to restart Apache and completely clear your browser cache.

Upvotes: 0

Zudwa
Zudwa

Reputation: 1400

You can add rewrite conditions for rewrite rule, and redirect will be performed only when they are met.

In your case you need first rule to check whether current request is not being done with https (To not to make an infinite redirect to same uri) and second for request uri and optionally host rule (In case you are using multiple host names, otherwise you can skip it). This code should work:

<VirtualHost *:80>
    ServerName example.com

    RewriteEngine on

    RewriteCond %{HTTP:PORT} !^443$ #Some other variants are available , but I prefer this one because not all work well on different environments
    RewriteCond %{REQUEST_URI} !^/ads$
    RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
    RewriteRule ^/(.*)$ https://www.example.com/$1 [QSA,L,R=301]
</VirtualHost>

All awailable variables and other code snippets can be found on official documentation page.

Upvotes: 0

Amr Aly
Amr Aly

Reputation: 3905

You can try something like

RewriteRule !^ads($|/) https://www.example.com%{REQUEST_URI} [L,R=301]

Upvotes: 1

Related Questions