数字海洋将非 www 重定向到 www

digital ocean redirect non-www to www

我正在尝试将我的域 http://example.com 重定向到 Digital Ocean 上的 http://www.example.com

我有 www 和 @ 的 A 记录,所以网站在每个域都可以访问,但重定向不起作用。这是我的默认配置文件 (/etc/nginx/sites-enabled/default) 中的内容:

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

root /var/www/app/deploy/frontend/;
index index.html index.htm;

# Make site accessible from http://localhost/
server_name example.com;

location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
}

#Redirect example.com to www.example.com

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

有什么想法吗?

正确的方法是在单独的服务器块中定义它们。可以像这样在同一个文件中:

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

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

创建 CNAME 记录 'yoursite.com' 是“@”的别名