Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

apache - How to write "if...else" mod_rewrite statements in .htaccess

I've scoured StackOverflow for an answer to this and seen many questions come close, but nothing is working for me yet.

I'd like to have my .htaccess apply different rules based on the domain calling it. Basically, if subdomain.example.com is hit, redirect to google.com. If localhost is hit, redirect to yahoo.com. If www.example.com (or example.com) is hit, redirect to bing.com.

I'll be adding in actual rewrite rules (setting environment variables and htpasswd protection) later, but first I need to get the "if then" part working.

My (non-working) code is below. Any help is greatly appreciated.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^subdomain.example.com$
RewriteRule http://google.com/ [L,R=301]

RewriteCond %{HTTP_HOST} ^localhost$
RewriteRule http://yahoo.com/ [L,R=301]

RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule http://bing.com/ [L,R=301]

EDIT: Updated (but still non-working) code based on Barta's comment below.

RewriteEngine On

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

RewriteCond %{HTTP_HOST} ^localhost$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
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$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .? - [S=1]
RewriteRule ^(.*)$ /index.php/$1 [L]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...