nginx如何让apache像虚拟主机一样?

时间:2015-02-09 09:02:55

标签: nginx centos7

我在CentOS 7中有这个配置:

$ cat /etc/nginx/conf.d/default.conf
server {
    listen       80;
    server_name  8.8.8.8;
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

我正在尝试制作虚拟主机配置,例如:

if visitor (www.domain1.com) then /usr/share/nginx/html/domain1
if visitor (www.domain2.com) then /usr/share/nginx/html/domain2

如何从请求所在的主机检入我的default.conf?这样我可以将它们路由到正确的目录?

1 个答案:

答案 0 :(得分:0)

CentOS 7:工作

第1步:

$ rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
$ yum install nginx php php-mysql php-fpm mariadb-server mariadb
$ systemctl start nginx.service
$ systemctl enable nginx.service
$ sudo systemctl start mariadb
$ sudo mysql_secure_installation
$ sudo systemctl enable mariadb.service
$ sudo vi /etc/php.ini
cgi.fix_pathinfo=0
$ sudo vi /etc/php-fpm.d/www.conf
listen = /var/run/php-fpm/php-fpm.sock
$ sudo systemctl start php-fpm
$ sudo systemctl enable php-fpm.service

第2步:VHost部分

$ sudo vi /etc/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  8.8.8.8;
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

server {
    listen       80;
    server_name  127.0.0.1;
    root   /usr/share/nginx/html/domain1;
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html/domain1;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

}

测试VHost:

$ curl http://8.8.8.8
$ curl http://127.0.0.1