How to write “if…else” mod_rewrite statements in .htaccess

a 夏天 提交于 2019-11-29 15:40:39
Jarrod

You might find this useful if you are using Apache 2.4.

My server sets an environment variable HTTPS if connecting via HTTPS, though there are different ways to pick up on it. My goal was to force HTTP authentication, but only on a secure connection and redirect non-secure connections to the secure location.

<If "%{HTTPS} == 'on'">
  AuthName "Files are protected, enter your normal website email and password"
  AuthType Basic
  AuthUserFile /home/sites/mysite.co.uk/.htpasswd
  Require valid-user
</If>
<Else>
  RewriteEngine On
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</Else>

You are trying to rewrite http://bing.com to [L,R=301] instead of anything to http://bing.com with the [L,R=301] flags. Try RewriteRule ^(.*)$ http://bing.com/ [L,R=301]

About IF-ELSE: Use the S flag on your RewriteRule like that:

RewriteCond %{HTTP_HOST} ^subdomain\.example\.com$
RewriteRule .? - [S=<here comes the number of your directives in the "else" part>]
# Here comes your ELSE part:
# Etc. etc.
RewriteRule .? - [S=<here comes the number of your directives in the "if" part>]
# Here comes your IF part.

In the example above if your RewriteCOnd is matched, then the RewriteRule with the S flag skips the following directives and stops the skipping after the Nth skip where N is defined after the S= part. This is your ELSE part. The N number should include your next RewriteRule that skips the IF part.

They are in reversed order, because of the skipping. If you negate the RewriteCond, then they're ok in normal order.

Here's the original example in Apache docs: https://httpd.apache.org/docs/2.2/rewrite/flags.html#flag_s

Edit: Try something like that:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^subdomain\.domain\.com$
RewriteRule .? - [S=1]
RewriteRule ^(.*)$ /index.php/$1 [L]

RewriteCond %{HTTP_HOST} !^localhost$
RewriteRule .? - [S=7]
RewriteRule ^(.*)$ /subdir/www/index.php/$1 [L]
RewriteRule ^ - [E=MYSQL_DB_HOST:localhost]
RewriteRule ^ - [E=MYSQL_DB_NAME:XXX]
RewriteRule ^ - [E=MYSQL_USERNAME:XXX]
RewriteRule ^ - [E=MYSQL_PASSWORD:XXX]
RewriteRule ^ - [E=BASE_URL:XXX]
RewriteRule ^ - [E=ENVIRONMENT:XXX]

RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule .? - [S=1]
RewriteRule ^(.*)$ /index.php/$1 [L]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!