nginx将所有通配符子域重写为www.site.com [英] nginx rewrite all wildcard subdomains to www.site.com

查看:69
本文介绍了nginx将所有通配符子域重写为www.site.com的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用nginx将example.com的所有子域重定向到www.example.com.

Using nginx, I want to redirect all subdomains of example.com to www.example.com.

我在这里看到重定向,可以将非www重定向到www,反之亦然,但是我也希望重定向www2.site.com blabla.site.com. 我有该域的通配符dns.

I have seen redirects here to redirect non-www to www or vise versa, but I also want www2.site.com blabla.site.com to be redirected. I have a wildcard dns for the domain.

对于Apache,可以通过以下操作轻松完成:

For apache this can be done easily with following:

RewriteCond %{HTTP_HOST} !www.example.com [NC]
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]

以下内容似乎可行,但根据 ifisevil页面,不建议这样做.. >

The below seem to work, but it is not recommended according to the ifisevil page.

if ($http_host !~ "www.site.com"){
    rewrite ^(.*)$ http://www.example.com$request_uri redirect;
}

推荐答案

在nginx中实现此目的的最佳方法是结合两个服务器块:

The best way to do this in nginx is with a combination of two server blocks:

server {
  server_name *.example.org;
  return 301 $scheme://example.org$request_uri;
}

server {
  server_name www.example.org;

  #add in further directives to serve your content
}

由于您报告笔记本电脑无法正常工作,因此我已经在笔记本电脑上对其进行了测试.我在本地得到以下结果(将www2.test.localhostwww.test.localhost/etc/hosts之后,并重新加载nginx):

I have tested this on my laptop, since you reported it not working. I get the following result locally (after adding www2.test.localhost and www.test.localhost to my /etc/hosts, along with the nginx config bit, and reloading nginx):

$ curl --head www2.test.localhost
HTTP/1.1 301 Moved Permanently
Server: nginx/1.2.6
Date: Thu, 07 Mar 2013 12:29:32 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://www.test.localhost/

是的,这肯定有效.

这篇关于nginx将所有通配符子域重写为www.site.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆