12.6 Nginx安装
cd /usr/local/srcwget http://nginx.org/download/nginx-1.12.2.tar.gztar xf nginx-1.12.2.tar.gzcd nginx-1.12.2./configure --prefix=/usr/local/nginx //这里故意不加其他参数, 以后再编译, 正常要根据自己的实际需求加上需要编译的参数, 如 --with-http_ssl_module make && make install
vim /etc/init.d/nginx //复制如下内容
参考
chmod 755 /etc/init.d/nginxchkconfig --add nginxchkconfig nginx oncd /usr/local/nginx/conf/ && mv nginx.conf nginx.conf.bak
vim nginx.conf //写入如下内容
参考
nginx.conf简单解析:user nobody nobody; //定义启动nginx的是哪个用户worker_processes 2; // 定义子进程有几个error_log /usr/local/nginx/logs/nginx_error.log crit; //错误日志pid /usr/local/nginx/logs/nginx.pid; //定义pidworker_rlimit_nofile 51200; //nginx 最多可以打开多少个文件use epoll; //使用epoll模式worker_connections 6000; //进程最大连接数每个server对应着1个虚拟主机如果想php监听的是ip 则写成:/usr/local/nginx/sbin/nginx -t/etc/init.d/nginx startnetstat -lntp | grep 80测试php解析vim /usr/local/nginx/html/1.php //加入如下内容 curl localhost/1.php
12.7 默认虚拟主机
去掉 usr/local/nginx/conf/nginx.conf 中 的内容Server {.....}vim /usr/local/nginx/conf/nginx.conf //增加include vhost/*.conf; //注意;号别漏, 在conf目录下加个vhost目录mkdir /usr/local/nginx/conf/vhostcd !$vim default.conf //加入如下内容server{ listen 80 default_server; // 有这个标记的就是默认虚拟主机 server_name 120.com; index index.html index.htm index.php; root /data/wwwroot/default;}mkdir -p /data/wwwroot/default/echo "This is a default site." >/data/wwwroot/default/index.html/usr/local/nginx/sbin/nginx -t/usr/local/nginx/sbin/nginx -s reloadcurl localhostcurl -x127.0.0.1:80 120.com
12.8 Nginx用户认证
vim /usr/local/nginx/conf/vhost/test.com.conf//写入如下内容
server{ listen 80; server_name test.com; index index.html index.htm index.php; root /data/wwwroot/test.com; location / { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd; }}yum install -y httpdhtpasswd -c /usr/local/nginx/conf/htpasswd aming -c 创建 -m md5加密, 第二次用不用 -c创建了mkdir /data/wwwroot/test.comecho "test.com">/data/wwwroot/test.com/index.htmlcurl -x127.0.0.1:80 test.com -I //状态码为401说明需要验证curl -uaming:passwd -x127.0.0.1:80 test.com -I 访问状态码变为200 passwd改为自己的aming的密码 -t && -s reload //测试配置并重新加载 编辑windows的hosts文件,然后在浏览器中访问test.com会有输入用户、密码的弹窗针对目录的用户认证location /admin/ { auth_basic "Auth"; auth_basic_user_file /usr/local/nginx/conf/htpasswd;}mkdir /data/wwwroot/test.com/adminecho "admin in test.com">/data/wwwroot/test.com/admin/index.html-t && -s reload //测试配置并重新加载针对单个文件location ~ admin.php // ~(.*)admin.php$ 更全面匹配 包含 admin php结尾的文件
12.9 Nginx域名重定向
更改test.com.conf
server{ listen 80; server_name test.com test1.com test2.com; index index.html index.htm index.php; root /data/wwwroot/test.com; if ($host != 'test.com' ) { rewrite ^/(.*)$ http://test.com/$1 permanent; }}permanent 301的意思, 想改成302用 redirectserver_name后面支持写多个域名,这里要和httpd的做一个对比permanent为永久重定向,状态码为301,如果写redirect则为302测试curl -x127.0.0.1:80 test1.com/1.php -i