12.6 Nginx安装
- cd /usr/local/src
- wget http://nginx.org/download/nginx-1.12.1.tar.gz
- tar zxvf nginx-1.12.1.tar.gz
- ./configure --prefix=/usr/local/nginx
- make
- make install
- vim /etc/init.d/nginx #编辑启动脚本文件,添加特定内容(参考https://coding.net/u/aminglinux/p/aminglinux-book/git/blob/master/D15Z/etc_init.d_nginx )
- chmod 755 /etc/init.d/nginx
- chkconfig --add nginx
- chkconfig nginx on
- cd /usr/local/nginx/conf/; mv nginx.conf nginx.conf.bak
- vim nginx.conf #编辑nginx配置文件(参考https://coding.net/u/aminglinux/p/aminglinux-book/git/blob/master/D15Z/nginx.conf)
- /usr/local/nginx/sbin/nginx -t #语法检查
- /etc/init.d/nginx start #启动nginx
- netstat -lntp |grep 80
- vim /usr/local/nginx/conf/nginx.conf #编辑nginx配置文件,增加如下内容
- mkdir /usr/local/nginx/conf/vhost
- cd !$; vim default.conf #加入如下内容
server
{
listen 80 default_server; #有这个标记的就是默认虚拟主机
server_name aaa.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 reload #重新加载
- curl localhost
- curl -x127.0.0.1:80 123.com
- 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 httpd
- htpasswd -c /usr/local/nginx/conf/htpasswd aming
- -t && -s reload #测试配置并重新加载
- mkdir /data/wwwroot/test.com
- echo “test.com”>/data/wwwroot/test.com/index.html
- curl -x127.0.0.1:80 test.com -I #状态码为401说明需要验证
- curl -uaming:passwd #访问状态码变为200
- 编辑windows的hosts文件,然后在浏览器中访问test.com会有输入用户、密码的弹窗
- 针对目录的用户认证,编辑虚拟主机配置文件,指定特定目录添加对应内容:
location /admin/
{
auth_basic "Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
12.9 Nginx域名重定向
- vim /usr/local/nginx/conf/vhost/test.com.conf #编辑虚拟主机配置文件,更改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;
}
}
- server_name后面支持写多个域名,和httpd的做一个对比
- permanent为永久重定向,状态码为301,redirect则为302