gpt4 book ai didi

redirect - Nginx 非 www 到 www 和 www 到非 www

转载 作者:太空宇宙 更新时间:2023-11-03 16:39:24 27 4
gpt4 key购买 nike

我正在使用 nginx on Rackspace cloud following a tutorial并且已经搜索了网络,但到目前为止无法对此进行排序。

出于 SEO 和其他原因,我希望 www.mysite.example 在 .htaccess 中正常访问 mysite.example

我的/etc/nginx/sites-available/www.example.com.vhost 配置:

server {
listen 80;
server_name www.example.com example.com;
root /var/www/www.example.com/web;

if ($http_host != "www.example.com") {
rewrite ^ http://example.com$request_uri permanent;
}

我也试过

server {
listen 80;
server_name example.com;
root /var/www/www.example.com/web;

if ($http_host != "www.example.com") {
rewrite ^ http://example.com$request_uri permanent;
}

我也试过了。第二次尝试都给出了重定向循环错误。

if ($host = 'www.example.com' ) {
rewrite ^ http://example.com$uri permanent;
}

我的 DNS 设置为标准:

site.example 192.192.6.8 A type at 300 seconds
www.site.example 192.192.6.8 A type at 300 seconds

(示例 IP 和文件夹已用于示例并在将来帮助人们)。我使用 Ubuntu 11。

最佳答案

HTTP解决方案

来自documentation , "正确的方法是为 example.org 定义一个单独的服务器":

server {
listen 80;
server_name example.com;
return 301 http://www.example.com$request_uri;
}

server {
listen 80;
server_name www.example.com;
...
}

HTTPS解决方案

对于那些想要包含 https://...

的解决方案的人
server {
listen 80;
server_name www.domain.example;
# $scheme will get the http protocol
# and 301 is best practice for tablet, phone, desktop and seo
return 301 $scheme://domain.example$request_uri;
}

server {
listen 80;
server_name domain.example;
# here goes the rest of your config file
# example
location / {

rewrite ^/cp/login?$ /cp/login.php last;
# etc etc...

}
}

注意:我最初没有在我的解决方案中包含 https://,因为我们使用负载均衡器并且我们的 https://服务器是高流量 SSL 支付服务器:我们不混合 https://和 http://。


要检查 Nginx 版本,请使用 nginx -v

使用 Nginx 重定向从 URL 中去除 www

server {
server_name www.domain.example;
rewrite ^(.*) http://domain.example$1 permanent;
}

server {
server_name domain.example;
#The rest of your configuration goes here#
}

所以你需要有两个服务器代码。

使用 Nginx 重定向将 www 添加到 URL

如果你需要的是相反的,从 domain.example 重定向到 www.domain.example,你可以使用这个:

server {
server_name domain.example;
rewrite ^(.*) http://www.domain.example$1 permanent;
}

server {
server_name www.domain.example;
#The rest of your configuration goes here#
}

如您所想,这与第一个示例正好相反,工作方式相同。这样,您就不会降低 SEO 标记,因为它是完整的 perm 重定向和移动。强制没有 WWW 并显示目录!

下面显示了我的一些代码以获得更好的 View :

server {
server_name www.google.com;
rewrite ^(.*) http://google.com$1 permanent;
}
server {
listen 80;
server_name google.com;
index index.php index.html;
####
# now pull the site from one directory #
root /var/www/www.google.com/web;
# done #
location = /favicon.ico {
log_not_found off;
access_log off;
}
}

关于redirect - Nginx 非 www 到 www 和 www 到非 www,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947030/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com