apache - .htaccess:子域、重写、SSL 和密码保护

标签 apache .htaccess mod-rewrite ssl

一段时间以来,我一直在为这个问题苦苦挣扎,但没有找到满足我所有需求的解决方案。 我有两个站点,example.com 和 example.de,我希望每个访问者总是被重定向到 www.example.com 此外,所有网址都必须翻译成相应的 www.example.com 网址。一些子文件夹受密码保护。 最重要的是,我为 example.com 使用了 SSL 证书

所以在几行中我希望 Apache 如下所示:

Visitor types this URL -> Apache redirects to (301)
http://example.de -> https://www.example.com
http://www.example.de -> https://www.example.com
http://example.com -> https://www.example.com
http://example.de/path/to/some/file.php -> https://www.example.com/path/to/some/file.php
http://example.de/stats (Login required) -> https://www.example.com/stats (Login required)

我尝试了几种 .htaccess 配置。我最好的结果成功地重定向了前四种情况:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]`

但是,我无法通过重定向访问受密码保护的文件夹。我的浏览器显示 401 错误消息(因为身份验证模块在重写模块之前执行)。有人有想法吗?

编辑: 这似乎是解决方案。我仍在测试,但看起来还不错。

/.htaccess

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteRule ^(.*)$ - [E=REWRITTEN:1]

/stats/.htaccess

AuthType Basic
AuthName "Members Only"
AuthUserFile /home/.htpasswd

Order Deny,Allow
Satisfy any
Deny from all
Require valid-user
Allow from env=!REWRITTEN

最佳答案

尝试:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.(com|de)$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

关于apache - .htaccess:子域、重写、SSL 和密码保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707878/

相关文章:

java - 为什么循环会覆盖初始代码,而不是创建新的 XSSFSheet?

apache - Htaccess 301 博客重定向 url

apache - 在 .htaccess 中使用 keep-alive 功能

apache - 仅使用我在 htaccess 上编写的 url 进行访问,防止访问真实的 url

php - Laravel 5.4 - 路线不工作

wordpress - 如何在 apache 中为 WordPress json API v1 和 v2 重写规则

regex - HTTPS 强制重定向在 Wordpress 中不起作用

apache - Camel 的 CXF 组件无法捕获 onException(Exception.class)

php - 无法在 codeigniter 3 中加载 css 文件

apache - 如何使.htaccess RewriteRule同时支持path和query_string