您的位置:首页 > 运维架构 > Nginx

nginx默认虚拟主机、用户认证、域名重定向

2018-01-03 14:55 1161 查看
Nginx默认虚拟主机

定义默认虚拟主机配置文件,在http下面加入include vhost/*.conf



在/usr/local/nginx/conf/下创建目录

#mkdir vhost/                           //创建vhost目录
#cd vhost/                              //进入目录

#vim aaa.com.conf                                       //编辑文件

server
{
listen 80 default_server; // 有这个标记的就是默认虚拟主机
server_name aaa.com;
index index.html index.htm index.php;
root /data/wwwroot/default;
}

#mkdir /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             //重新加载nginx

#curl   -x127.0.0.1:80    aaa.com                          //测试

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;               //密码所在的位置文件
}
}

htpasswd是apache的一个工具,该工具主要用于建立和更新存储用户名、密码的文本文件,主要用于对基于http用户的认证。htpasswd的安装很简单,它是随apache的安装而生成。

#yum install -y httpd                                                  //下载httpd包

#htpasswd -c /usr/local/nginx/conf/htpasswd zenwen                      //生成密码文件

#/usr/local/nginx/sbin/nginx  -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 -uzenwen:passwd -x127.0.0.1:80 test.com -I               // 访问状态码变为200




针对目录的用户认证
当访问admin时,只需要在location /加上admin目录就可以对admin进行用户的验证
location  /admin/
{
auth_basic              "Auth";
auth_basic_user_file   /usr/local/nginx/conf/htpasswd;
}

nginx域名重定向

更改test.com.conf
server{
listen 80;
server_name test.comtest1.comtest2.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

# /usr/local/nginx/sbin/nginx  -t                  //检测语法

#/usr/local/nginx/sbin/nginx  -s reload           //重新加载

#curl -x127.0.0.1:80 test2.com/index.html  -I                      //测试

HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 02:45:07 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html //直接重定向到了test.com

#curl -x127.0.0.1:80 test1.com/index.html  -I                     //显示状态码为301

HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Wed, 03 Jan 2018 06:53:13 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux nginx 配置
相关文章推荐