【nginx】nginx 配置那些事儿

来源:互联网 发布:js 点击radio 触发事件 编辑:程序博客网 时间:2024/06/16 05:53

nginx 是一款具有高负载能力的 web 服务器,也是 LNMP 架构的主要角色之一。现在越来越多的开发者选择 nginx 作为 php 的好搭档,替代 apache 的位置。下面我以 Mac 系统为例,介绍下 nginx 的配置

基本配置

打开 nginx.conf,找到 http 下的 server,前几行的内容分别是:

listen  8080;                #监听端口server_name  localhost;      #本地域名root  /usr/local/var/www;    #项目根目录

nginx 默认监听 8080 端口,你可以改成 80 端口。默认项目根目录也可以更改。不过更改之后要重新载入配置文件才能生效:

sudo nginx -s reload

注意:如果你不喜欢 localhost ,你想要一个个性的本地域名,比如 www.test.com ,首先要编辑 hosts 文件:

sudo vim /etc/hosts

添加一条:

127.0.0.1     www.test.com

然后修改 nginx.conf:

server_name    www.test.com

总之 nginx.conf 中设置的域名,必须在 hosts 文件中存在!

隐藏入口文件

在我们开发项目的时候,一般会有隐藏入口文件的需求。依然是在 http 下的 server,我们找到 location / ,在大括号内做修改。切记 ci 框架和 tp 框架的写法稍有不同,具体如下:

location / {       index  index.php index.html index.htm;       if (!-e $request_filename) {            rewrite ^/(.*)$ /index.php?$1 last;    #ci框架写法            #rewrite ^/(.*)$ /index.php?s=/$1 last;    #tp框架写法            break;       }}

如果你用的是 tp5 , 入口文件在 public 目录下,但是你不想在URL中写 localhost/public/ 访问入口文件,你想直接通过 localhost/ 访问,你可以这样写:

rewrite ^/(.*)$ /public/index.php?s=/$1 last;

其实隐藏入口文件就是 nginx 做了下路由,看懂它的正则,其实不难理解。

解析php

如果要 nginx 正常解析 php,首先要在安装好 php 之后,启动 php-fpm。启动方法:

sudo php-fpm -D

上一步完成之后,接下来还是要修改 nginx.conf。server 下找到 location ~ \.php$ 这一行,包括它后面 {} 中的内容,去掉注释,也就是去掉前面的 # 号,修改成这样:

location ~ \.php$ {      fastcgi_pass   127.0.0.1:9000;      fastcgi_index  index.php;      fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;      fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;      fastcgi_param  PATH_INFO  $fastcgi_path_info;      fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;      include        fastcgi_params;}

如图:

重新载入配置文件。此时 nginx 就可以配合 php-fpm 正确解析 PHP 了。

多站点设置

前面我们修改配置文件的代码位置,都是在 http 下的 server 里。其实一个 server 就相当于一个站点。nginx.conf 下 http 模块默认开启一个 server,就是只有一个站点。如果我们要多站点,就需要添加多个 server。

现在我们要添加一个站点,假设这个站点的域名是 www.test2.com , 但是 server 不写在 nginx.conf 里。nginx 为我们提供了存放多站点配置文件的目录,我们切换到这个目录:

cd /usr/local/etc/nginx/servers/

然后新建配置文件:

vim www.test2.com.conf

里边写一个 server:

server {    listen  80;    server_name  www.test2.com;    index  index.html index.php;    root  /usr/local/var/test2;    location / {         index  index.php index.html;         rewrite ^/(.*)$ /public/index.php?s=/$1 last;         break;    }    location ~ \.php$ {        fastcgi_pass   127.0.0.1:9000;        fastcgi_index  index.php;        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;        fastcgi_split_path_info  ^((?U).+\.php)(/?.+)$;        fastcgi_param  PATH_INFO  $fastcgi_path_info;        fastcgi_param  PATH_TRANSLATED  $document_root$fastcgi_path_info;        include        fastcgi_params;    }    }

保存退出,重新载入配置文件。最后在 hosts 中添加:

127.0.0.1   www.test2.com

此时, www.test2.com 就可以访问到你的新项目目录 /usr/local/var/test2 下了!

0 0