linux - Apache 重写 URI,捕获页面/文件夹

标签 linux apache mod-rewrite url-rewriting httpd.conf

我正在尝试完成以下...如果用户通过 123abc.com(带或不带 www)123abc.com/hello(带或不带 www) 它们应该自动转到 https://www .123abc.com/URI_IF_NEED ...

这就是我目前所拥有的。基本域重定向正确,但任何带有 pages/dir 的 URL 结构都不会。

努力实现 https://www.123abc.com和/或 https://www.123abc.com/hello

ServerName www.123abc.com
ServerAlias 123abc.com
DocumentRoot "/mnt/var/www/html/"

RewriteEngine on
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

最佳答案

您不需要为此进行复杂的重写。只需创建不同的虚拟服务器,然后让 non-wwwwww(443/https) 上重定向,并在 (80/http) 上重定向一个 (80/http)

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    Redirect permanent / https://www.example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

PS:学分apache redirect from non www to www

如果你还想像以前那样写,那么你可以像下面这样写

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI}   [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI}   [R=301,L]

在在线测试仪上测试

https://htaccess.madewithlove.be/

不同的测试结果

Test 1

Test 2

Test 3

Test 4

关于linux - Apache 重写 URI,捕获页面/文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49985446/

相关文章:

linux - screenrc 中的 shell 命令

linux - VirtualHost 配置覆盖主域

regex - 某些查询参数/值对的 RewriteCond 匹配

.htaccess - RewriteRule 正在重定向到绝对路径,而不是正确的 URL

apache - 从 http 基本身份验证中排除特定的 cakephp Controller

c - 为什么 Linux TAP 设备不处理 ARP 或 ICMPv6 数据包

linux - Gtk警告: Modulpath »clearlooks« no Themen-Engine found

linux - 使用 sed 将起始字符更改为另一个字符

java - Java 中 RequestConfig 的 Python 等价物是什么?

apache - 重定向子域第一条