qwertzman
qwertzman

Reputation: 792

regex in .htaccess: force http with optional params, lead the rest to https

Good day!

I'm trying to redirect to http the following:
- module/run
- module/run/
- module/run/d{3} (matching natural number with 3 digits)
The rest should go to https for example module/rundmc

So I'm trying to make things optional but am failing:

CODE

# ######################################################################
# → Forcing `https://` with exception(s)
RewriteCond %{HTTPS} !=on
RewriteCond %{THE_REQUEST} !/module/run(/d{3})?$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,QSA]

# → Forcing http:// for selected URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /module/run(/d{3})?$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,QSA]

I can't figure it out, as soon as I add the $ sign to it it stops working.

Thank you kind person of the interwebz.

edit: Maybe I should explain why I'm asking the question: pages like /module/rundmc are also forced to http but I just need the 3 scenarios listed above.

Upvotes: 1

Views: 29

Answers (1)

anubhava
anubhava

Reputation: 785651

THE_REQUEST has much more stuff after REQUEST_URI. Example value of this variable is GET /index.php?id=123 HTTP/1.1

You can use:

# ######################################################################
# → Forcing `https://` with exception(s)
RewriteCond %{HTTPS} !=on
RewriteCond %{THE_REQUEST} !/module/run(/\d{3}|/)?[\s?] [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

# → Forcing http:// for selected URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} !/module/run(/\d{3}|/)?[\s?] [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

Upvotes: 1

Related Questions