nginx服务器配置:子域到文件夹

时间:2012-02-10 19:08:34

标签: nginx subdomain rewrite

我从Apache 2迁移到nginx,我遇到了问题,以便我的子域名控制。 我想要的:当请求x.domain.tld时,内部重写到domain.tld / x

我遇到的问题是nginx总是通过告诉浏览器重定向来重定向页面。但我真正想要的是在内部执行此操作,就像Apache 2那样。 另外,如果我只请求x.domain.tld,则nginx返回404.它仅在我执行x.domain.tld / index.php时有效

这是我的配置:

server {
        listen      80 default;
        server_name _ domain.tld www.domain.tld ~^(?<sub>.+)\.domain\.tld$;

        root /home/domain/docs/;

        if ($sub) {
                rewrite (.*) /$sub;
        }

        # HIDDEN FILES AND FOLDERS
        rewrite ^(.*)\/\.(.*)$ @404 break;

        location = @404 {
                return 404;
        }

        # PHP
        location ~ ^(.*)\.php$ {
                if (!-f $request_filename) {
                        return 404;
                }

                include       /etc/nginx/fastcgi_params;
                fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
        }
}

谢谢!

4 个答案:

答案 0 :(得分:8)

当我在寻找同一问题的解决方案的同时在谷歌上发现这个Q&amp; A时,我想发布我最终使用的解决方案。


MTeck的第一个服务器块看起来非常不错,但是对于子域部分,您可以简单地执行以下操作:

server {
  listen 80;
  server_name "~^(?<sub>.+)\.domain\.tld$";

  root /path/to/document/root/$sub;

  location / { try_files $uri $uri/ /index.php; }

  location ~ \.php {
    include fastcgi_params;
    fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
  }
}

这使得root配置指令依赖于子域。

答案 1 :(得分:3)

我花了好几个小时撞在墙上,这对我有用

server {
    listen       80;

    server_name ~^(?P<sub>.+)\.example\.com$; #<-- Note P before sub, it was critical for my nginx
    root /var/www/$sub; #<-- most important line cause it defines $document_root for SCRIPT_FILENAME

    location / {
            index index.php index.html; #<-- try_files didn't work as well
    }

    location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000; #<-- probably you have another option here e.g. fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
            include        fastcgi_params;
    }
}

答案 2 :(得分:1)

你应该看看http://wiki.nginx.org/IfIsEvil。你在这个配置文件中做错了很多。

server {
    server_name domain.tld www.domain.tld;

    location / {
        try_files $uri /index.php;
    }

    location ~ \.php {
        include fastcgi_params;
        fastcgi_pass  unix:/etc/nginx/sockets/domain.socket;
    }
}

server {
    server_name "~^(?<sub>.+)*\.(?<domain>.*)$";
    return 301 $scheme://$domain/$sub$request_uri;
}

如果你想要的是保持内部,你将无法重写它。根据定义,需要将跨站点重写发送回浏览器。您必须代理请求。

server {
    server_name "~^(?<sub>.+)*\.(?<domain>.*)$";
    proxy_pass http://$domain/$sub$request_uri;
}

你应该阅读Nginx维基。所有这些都得到了深入的解释。

答案 3 :(得分:0)

这也适用于www。

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    index index.php index.html index.htm index.nginx-debian.html;
    server_name ~^www\.(?P<sub>.+)\.domain\.com$ ~^(?P<sub>.+)\.domain\.com$;
    root /var/www/html/$sub;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }
}
相关问题