nginx 重写规则从主域到子域

标签 nginx rewrite

在我的 nginx domain.cong 中,我写了以下重写规则...... 当请求到达主域(有或没有 www)时,它应该重定向到博客子域,但它似乎是错误的......

server {
....
##### Rewrite rules for domain.tld => www.domain.tld #####
if ($host ~* ^([^.]+\.[^.]+)$) {
    set $host_without_www $1;
    rewrite ^(.*) $scheme://www.$host_without_www$1 permanent;
}

##### Rewrite rules for www.domain.tld => subdomain.domain.tld #####
if ($host ~* 'www\.[^.]+\.[^.]+$')  {
    set $host_without_www $1.$2;
    rewrite ^(.*) $scheme://subdomain.$host_without_www$1 permanent;
} 
...
} 

第一条规则是正确的:
domain.tld => www.domain.tld
但不是第二个只给
www.domain.tld => 子域。
应该是
www.domain.tld => subdomain.domain.tld

最佳答案

您的设置似乎有点过于复杂,在“if”中匹配 $host 并不是最佳做法。 如果您只有一个域,那很简单:

server {
    # ...
    server_name domain.tld www.domain.tld;
    return 301 $scheme://subdomain.domain.tld$request_uri;
}

server {
    server_name subdomain.domain.tld;
    # ...
}

如果您有很多域,设置类似,只需使用正则表达式并在 server_name 捕获变量

关于nginx 重写规则从主域到子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324351/

相关文章:

python - 在生产中,Apache + mod_wsgi 还是 Nginx + mod_wsgi?

ruby-on-rails - 使用 Nginx 和 Puma Rails 提供静态文件

Wordpress - 将查询字符串作为基于斜杠的 URL 传递

nginx 重写而不更改 url

.htaccess url 重写不工作

networking - 主机无法访问Docker容器

Spring - nginx 中的邮件发件人

django - React请求Django API时,出现net::ERR_SSL_PROTOCOL_ERROR

if-statement - 使用 Puppet Nginx jfryman 模块将 if else 放入 nginx Vhost 配置中

git - 我怎样才能轻松修复过去的提交?