我的Web开发之旅-入坑nginx

LAMP组合用了很长时间,最近实在受不了Apache了。本来就是加个虚拟主机,折腾好长时间也没搞定,网上找一堆教程不管用,去官网查文档依然没找到问题在哪,一堆活压在手里,心急如焚的我没了耐性,决定试试nginx。

其实慕名nginx很久了,一直安于LAMP的组合,没有着手去尝试,借此机会尝试一下。结果一试不要紧,在Apache那儿没有的耐性,在nginx这儿全磨出来了。原来nginx并不是我想象中的“傻白甜”。

一、Ubuntu apt-get安装

我的系统Ubuntu Server 16.04,安装前我先卸载了apache,安装nginx提示已安装,无需更新,难道是装系统的时候选了nginx安装包?不去计较,直接启动之。之后并不顺利,因为nginx配置文件和之前所使用的apache的写法简直不是一个套路,网上看了很多例子,终于能跑出静态页面了。然而打开php页面,浏览器直接给下载了下来,这实在是个“惊喜”。原来nginx不像apache,已经集成了cgi,所以需要额外安装,我直接安装了php-fpm。又在网上搜罗一堆博文,比葫芦画瓢终于见到了php的页面。到了虚拟主机,却又难住了,折腾许久,配置到最后发现if指令并不能工作,想到可能是版本的原因,那没有办法,只能源码编译安装了。

二、源码编译安装

wget http://nginx.org/download/nginx-1.13.8.tar.gz

tar zxvf nginx-1.13.8.tar.gz

./configure

make

make install

一路倒是顺利,安装目录是默认的/usr/local/nginx/,配置文件是conf/nginx.conf,可执行文件是sbin/nginx,打一个软连接:

ln -s /usr/local/nginx/sbin/nginx /usr/bin/nginx

三、命令行指令

nginx -h显示如下:

nginx version: nginx/1.13.8
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-T : test configuration, dump it and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /usr/local/nginx/)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file

最常用的是重新输入配置文件,调试配置文件是很有用:

nginx -s reload

三、配置文件

最主要就是server这一部分了

server {
listen 80;
server_name www.oceiot.com oceiot.com;

set $root_path ‘/opt/www/public’; #定义root_path变量,设置默认的root路径
if ($uri ~ ^/phpmyadmin*) { #通过if指令判断要访问的子目录,并定义root路径
set $root_path ‘/opt/www’;
}
if ($uri ~ ^/public*) {
set $root_path ‘/opt/www’;
}

root $root_path; #使root_path生效

index index.php index.html index.htm;

try_files $uri $uri/ @rewrite; #找不到文件时重写uri

location @rewrite {
rewrite ^/(.*)$ /index.php?_url=/$1; #重写uri到root_path下的index.php,并传递原始uri
}

#匹配php文件,包括上面rewrite后的uri,转到fast cgi,

location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index /index.php;

fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

#拒绝访问ht文件

location ~ /\.ht {
deny all;
}
}

The school posts a monthly newsletter to inform parents of upcoming events and other important information buyresearchpapers.net.