Apache: Перенаправьте все с www на не-www, используя только https (включая HSTS)

Моя цель

Все приводит к https: //mydomain.tld ([ без www и с TLS ) и HSTS работает правильно. Я использую сертификаты от LE (Let's Encrypt), поэтому я использовал их мастер, чтобы сделать свой сайт HTTPS везде. Но, похоже, это работает неправильно.

Мои текущие проблемы

  1. Посещение http: //mydomain.tld ( без www, без TLS ). Результат Я использую сертификаты от LE (Let's Encrypt), поэтому я использовал их мастер, чтобы сделать свой сайт HTTPS везде. Но, похоже, это работает неправильно.

    Мои текущие проблемы

    1. Посещение http: //mydomain.tld ( без www, без TLS ). Результат Я использую сертификаты от LE (Let's Encrypt), поэтому я использовал их мастер, чтобы сделать свой сайт HTTPS везде. Но, похоже, это работает неправильно.

      Мои текущие проблемы

      1. Посещение http: //mydomain.tld ( без www, без TLS ). Результат страницу статуса Apache, но у меня уже есть сайт, работающий с содержание. При перезагрузке страницы появляется https: //mydomain.tld с контент-сайт. Но он должен делать это с первого взгляда и не только после перезагрузки страницы.
      2. Посещение http: //www.mydomain.tld приводит к https: //www.mydomain.tld это нормально для TLS-просмотра, но не перенаправляет на не-www, что является моей целью.
      3. Посещение https: //www.mydomain.tld возобновляется в https: //www.mydomain.tld . Нет перенаправления на не-www.
      4. Нет проблем: Посещение https: //mydomain.tld приводит к тому же URL-адресу, что я и хочу.

      Настройки DNS:

      A-RECORDS
      .mydomain.tld -> 111.222.333.444
      *.mydomain.tld -> 111.222.333.444
      www.mydomain.tld -> 111.222.333.444
      

      mydomain.tld.conf

      <VirtualHost *:80>
      
      ServerName mydomain.tld
      ServerAlias www.mydomain.tld
      ServerAdmin contact@mydomain.tld
      DocumentRoot /var/www/mydomain.tld/public_html
      Redirect permanent / https://mydomain.tld/
      
      <Directory /var/www/mydomain.tld/public_html>
      Options FollowSymLinks
      AllowOverride all
      Require all granted
      </Directory>
      
      ErrorLog ${APACHE_LOG_DIR}/error.log
      CustomLog ${APACHE_LOG_DIR}/access.log combined
      
      RewriteEngine On
      RewriteCond %{HTTPS} off
      RewriteRule (.*) https://%{SERVER_NAME}/%$1 [R,L]
      </VirtualHost>
      

      mydomain.tld-le-ssl.conf

      <IfModule mod_ssl.c>
      <VirtualHost *:443>
              ServerName www.mydomain.tld
              ServerAlias mydomain.tld
              ServerAdmin contact@mydomain.tld
              DocumentRoot /var/www/mydomain.tld/public_html
      
              <Directory /var/www/mydomain.tld/public_html>
              Options FollowSymLinks
              AllowOverride all
              Require all granted
              </Directory>
      
              ErrorLog ${APACHE_LOG_DIR}/error.log
              CustomLog ${APACHE_LOG_DIR}/access.log combined
      
      Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
      
      RewriteEngine on
      SSLCertificateFile /etc/letsencrypt/live/mydomain.tld/fullchain.pem
      SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.tld/privkey.pem
      Include /etc/letsencrypt/options-ssl-apache.conf
      
      </VirtualHost>
      </IfModule>
      

      Как вы можете видеть выше в mydomain.tld-le-ssl.conf , включен еще один файл, который может не создавать проблем, но только для записей:

      options-ssl-apache.conf

      # Baseline setting to Include for SSL sites
      
      SSLEngine on
      
      # Intermediate configuration, tweak to your needs
      SSLProtocol             all -SSLv2 -SSLv3
      SSLCipherSuite          ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA$
      SSLHonorCipherOrder     on
      SSLCompression          off
      
      SSLOptions +StrictRequire
      
      # Add vhost name to log entries:
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" vhost_combined
      LogFormat "%v %h %l %u %t \"%r\" %>s %b" vhost_common
      
      #CustomLog /var/log/apache2/access.log vhost_combined
      #LogLevel warn
      #ErrorLog /var/log/apache2/error.log
      
      # Always ensure Cookies have "Secure" set (JAH 2012/1)
      #Header edit Set-Cookie (?i)^(.*)(;\s*secure)??((\s*;)?(.*)) "$1; Secure$3$4"
      

      Bonus-problem

      У меня есть файл .htaccess в моем корневом домене что улучшает внешний вид ссылок:

      • без: https: //mydomain.tld/index.php? page = news
      • с: https: //mydomain.tld/news

      .htaccess

      RewriteEngine On
      
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^\w+$ index.php?page=$0 [L]
      RewriteCond %{THE_REQUEST} index\.php
      RewriteCond %{QUERY_STRING} ^page=(\w+)$
      RewriteRule ^index\.php$ /%1? [R=301,L]
      

      Я бы хотел жить без файла .htaccess и, если возможно, добавить его в .conf-файл (ы), но все, что я сделал, не было ' пока не работает.

0
задан 3 February 2016 в 01:26
1 ответ

Это странно. Вчера я создал новые сертификаты, и они все еще работали. Сегодня:

  • Chrome (мобильный): http: //mydomain.tld правильно перенаправляет на https: //mydomain.tld

  • Firefox (рабочий стол): http: //mydomain.tld не перенаправляет и приводит к Apache-странице

  • Firefox (мобильный), которой никогда не было на моем веб-сайте: То же, что и Firefox (рабочий стол)

  • Safari (мобильный), которого никогда не было на моем веб-сайте: То же, что и Firefox (рабочий стол)

Кажется, проблема все еще существует. Было бы здорово получить помощь, чтобы наконец решить эту проблему.

Решение этой проблемы:

  • $ sudo a2dissite 000-default.conf
  • Удалите все, что указано ниже, в mydomain.tld.conf:

RewriteEngine On RewriteCond% {HTTPS} выкл. RewriteRule (. *) Https: //% {SERVER_NAME} /% $ 1 [R, L] RewriteRule ^ https: //% {SERVER_NAME}% {REQUEST_URI} [END, QSA, R = постоянный]

Просто используйте: Перенаправление постоянное / https: //mydomain.tld

  • $ sudo /etc/init.d/apache2 restart

Окончательные файлы

mydomain.tld.conf

<VirtualHost *:80>

ServerName mydomain.tld
ServerAlias www.mydomain.tld
ServerAdmin contact@mydomain.tld
DocumentRoot /var/www/mydomain.tld/public_html
Redirect permanent / https://mydomain.tld

<Directory /var/www/mydomain.tld/public_html>
Options FollowSymLinks
AllowOverride all
Require all granted
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

mydomain.tld-le-ssl.conf

LoadModule headers_module modules/mod_headers.so

<IfModule mod_ssl.c>
<VirtualHost *:443>
Header always set Strict-Transport-Security "max-age=63072000; includeSubdomain$

ServerName mydomain.tld
ServerAlias www.mydomain.tld
ServerAdmin contact@nmydomain.tld
DocumentRoot /var/www/mydomain.tld/public_html

<Directory /var/www/mydomain.tld/public_html>
Options FollowSymLinks
AllowOverride all
Require all granted

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^\w+$ index.php?page=$0 [L]
RewriteCond %{THE_REQUEST} index\.php
RewriteCond %{QUERY_STRING} ^page=(\w+)$
RewriteRule ^index\.php$ /%1? [R=301,L]

</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

RewriteEngine on
SSLCertificateFile /etc/letsencrypt/live/mydomain.tld/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.tld/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]
</VirtualHost>
</IfModule>
0
ответ дан 5 December 2019 в 10:43

Теги

Похожие вопросы