.htaccess

.htaccess

我需要始终用 www.domain.com 替换 domain.com 并强制使用 https,因此最终结果应该始终是https://www.domain.com当请求 domain.com 或 www.domain.com 时,我尝试了以下操作,网站仍然可以通过 https 访问,但不会强制使用 www:

.htaccess

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

nginx

server {
    listen 80;
    server_name domain.com;

    return 301 $scheme://www.domain.com$request_uri;
}

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  www.domain.com;
        root         /path/to/project;
        location / {
                try_files $uri /app.php$is_args$args;
        }
        location ~ ^/(app_dev|config)\.php(/|$) {
                fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_split_path_info ^(.+\.php)(/.*)$;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root;
        }
        location ~ ^/app\.php(/|$) {
                fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
                fastcgi_split_path_info ^(.+\.php)(/.*)$;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT $realpath_root;
                internal;
        }
        location ~ \.php$ {
                return 404;
        }
        location ~ /\. {
                deny all;
        }
        location ~ /.well-known {
                allow all;
        }
        error_log /path/to/error.log;
        access_log /path/to/access.log;
}
server {
        listen 443 ssl;

        server_name  www.domain.com;

        ..rest of code..
}

nginx 另一种方法

server {
    listen      80;
    server_name domain.com;
    rewrite     ^   https://www.domain.com$request_uri? permanent;
}

在搜索中找到了其他几种方法,但似乎对我都不起作用,如果能得到任何帮助,我将不胜感激。提前致谢。

答案1

HTTP 到 HTTPS:

server {
        listen 80;
        server_name *;
        location / {
                return 302 https://$host$request_uri;
        }
}

非 WWW 到 WWW:

server {
        server_name domain-without-www.com;
        listen 443 ssl;
        location / {
                return 302 https://www.$host$request_uri;
        }
}

确保用 having 替换域并具有额外的server块。server_namewww.domain.com

答案2

我找到了可供参考的解决方案:

对于 http

location / {
           if ($http_host !~ "^www\."){
                  rewrite ^(.*)$ http://www.$http_host$1 redirect;
           }
           try_files $uri /app.php$is_args$args;
}

对于 https

location / {
        if ($http_host !~ "^www\."){
                rewrite ^(.*)$ https://www.$http_host$1 redirect;
        }
        try_files $uri /app.php$is_args$args;
}

相关内容