“if...else"怎么写?.htaccess 中的 mod_rewrite 语句 [英] How to write "if...else" mod_rewrite statements in .htaccess
问题描述
我已经在 StackOverflow 上搜索了这个问题的答案,看到很多问题都很接近,但还没有对我有用.
I've scoured StackOverflow for an answer to this and seen many questions come close, but nothing is working for me yet.
我想让我的 .htaccess
根据调用它的域应用不同的规则.基本上,如果 subdomain.example.com 被点击,重定向到 google.com.如果命中 localhost,则重定向到 yahoo.com.如果点击 www.example.com(或 example.com),则重定向到 bing.com.
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.
稍后我将添加实际的重写规则(设置环境变量和 htpasswd 保护),但首先我需要让if then"部分工作.
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]
根据下面 Barta 的评论更新(但仍然无效)代码.
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]
推荐答案
如果您使用的是 Apache 2.4,您可能会发现这很有用.
You might find this useful if you are using Apache 2.4.
如果通过 HTTPS 连接,我的服务器会设置一个环境变量 HTTPS
,尽管有不同的方法可以获取它.我的目标是强制进行 HTTP 身份验证,但仅限于安全连接并将非安全连接重定向到安全位置.
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>
这篇关于“if...else"怎么写?.htaccess 中的 mod_rewrite 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!