(Nginx)正则表达式模式匹配除www之外的所有内容

时间:2014-07-07 15:10:27

标签: regex nginx pcre

基本上,我尝试使用正则表达式设置nginx以便它:

  • 匹配pyronexus.com&的所有子域名notoriouspyro.com但不是www(www被重定向到pyronexus.com)。
  • 给我一个变量,我可以用它来确定子域和域输入的内容(例如,如果有人输入space.pyronexus.com,我想有两个变量$ subdomain和$ domain包含空格和pyronexus)。

到目前为止,我有:~^(.*)\.(?:pyronexus|notoriouspyro)\.com$

但我似乎无法弄清楚其他任何事情!任何帮助将不胜感激。

编辑:也许有助于显示我的nginx配置文件:

server {
    server_name pyronexus.com notoriouspyro.com;
    listen 127.0.0.1:80 default_server;

    root /home/nginx/pyronexus.com/public;
    index index.html index.php;

    access_log /home/nginx/pyronexus.com/logs/access.log;
    error_log /home/nginx/pyronexus.com/logs/error.log;

    include php.conf;
}

server {
    server_name ~^(www\.)?(.+)$;
    listen 127.0.0.1:80;

    return 301 $scheme://$2$request_uri;
}

第一部分是我需要正则表达式的服务器,第二部分是尝试捕获登陆www的所有域并在没有www的情况下重定向它们。

3 个答案:

答案 0 :(得分:1)

这种模式似乎是这样做的:

^((?!www).+?)\.(?:pyronexus|notoriouspyro)\.com$

Regular expression to match a line that doesn't contain a word?提供

在这里测试:

http://regex101.com/r/yK7oE2/1

如果您需要域名,只需省略?:

^((?!www).+?)\.(pyronexus|notoriouspyro)\.com$

答案 1 :(得分:1)

退后一步。任务是:

  • 在pyronexus.com和notoriouspyro.com上提供网站
  • 将子域重定向到各自的域
  • 将www子域名重定向到pyronexus.com

因此,不要使用过于复杂的正则表达式,而是制作三个服务器块。任务列表中的第二个是全部捕获。

答案 2 :(得分:1)

这很简单,就像@Melvyn说的那样,你在想这个,你需要一个捕获所有服务器来处理所有域,然后创建一个特定的服务器来重定向www。

您想要了解您正在访问的主机的最佳变量是$http_host

server {
  listen 80 default_server;
  # here handle all subdomains, this will also match the non-www domains of
  # the both domains
}
server {
  listen 80;
  server_name www.pyronexus.com;
  return 301 http://pyronexus.com$request_uri;
}
server {
  listen 80;
  server_name www.notoriouspyro.com;
  return 301 http://notoriouspyro.com$request_uri;
}
相关问题