使用.htaccess强制子域的SSL HTTPS

haa*_*kym 5 php apache .htaccess mod-rewrite ssl

我有这个代码一般在网站上强制使用SSL:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)

我从这里得到了什么

我希望它只适用于特定的子域.

例如,如果您要访问http://sub.domain.org它,则应重定向到https://sub.domain.org.

我有一种预感,我需要添加另一个RewriteCond,基本上说是被击中的域名是http://sub.domain.org,但我对如何编写此代码感到茫然.

我一直在寻找其他stackoverflow问题,例如:

强制域的HTTPS和WWW以及子域HTACESS的HTTPS

使用.htaccess和mod_rewrite强制SSL/https

和Apache文档:https://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

我有过这些尝试:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^(reports\.)?uksacb\.org$ [NC]
RewriteRule ^.*$ https://%1%{REQUEST_URI} [R,L]
Run Code Online (Sandbox Code Playgroud)

在这个问题/答案中,有点颠倒了答案:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} =reports.uksacb.org
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)

但是我仍然没有理解如何正确地做到这一点.

如果有人能够向我解释我做错了什么,我需要做些什么才能做到正确,如何调试他们的重写条件和规则以确保它正常工作我会非常感激.有时我认为我的浏览器正在缓存我写的规则,我的不同尝试没有任何影响!

我的整个.htaccess看起来像这样:

选项-MultiViews

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Run Code Online (Sandbox Code Playgroud)

Rus*_*n P 12

为了避免使用我曾经使用的域名或子域名,请使用以下代码:

  # Redirect HTTP to HTTPS
  RewriteCond %{HTTPS} off
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)

我更喜欢没有WWW.

%{HTTPS}如果请求是通过SSL提供的,则设置为on.

%{HTTP_HOST}协议(http://或https://)与请求(/example-file.txt)之间的所有内容.

%{REQUEST_URI}服务器地址之后的所有内容 - 例如,对http://example.com/my/example-file.txt的请求将此值设置为my/example-file.txt.

%{HTTP:X-Forwarded-Proto}请求URL时使用的协议 - 设置为http或https.

我希望它对任何人都有用.


Flo*_*ian 1

为了调试,我使用我找到的网站https://htaccess.madewithlove.be/

使用您提供的规则

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Run Code Online (Sandbox Code Playgroud)

我在以下位置遇到错误

RewriteCond %{HTTPS} !=on
Run Code Online (Sandbox Code Playgroud)

这可能对你有用

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/%$1 [R,L] 
Run Code Online (Sandbox Code Playgroud)

在https://www.sslshopper.com/apache-redirect-http-to-https.html找到上面的示例