码迷,mamicode.com
首页 > 其他好文 > 详细

nginx常用配置系列-虚拟主机

时间:2017-06-26 22:39:28      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:页面   需要   pre   div   location   代理   监听   http   root   

本来准备详尽的出一份nginx配置讲解,但nginx功能配置繁多,平常使用中使用最多的一般有:

1. 虚拟主机配置

2. HTTPS配置

3. 静态资源处理

4. 反向代理

================= 虚拟主机配置 =================

先说虚拟主机配置,nginx的核心配置文件在nginx的安装目录下conf目录中(如果是CentOS通过yum安装则在/etc/nginx目录中)

在conf目录下创建vhost目录,方便管理虚拟主机的配置文件

mkdir vhost

以example.com域名为例,在vhost目录中新建虚拟主机的配置文件example.com.conf(文件名依照域名来构造,方便辨别),编辑example.com.conf(下面是一段PHP虚拟主机的典型配置)

server {
    # 监听的端口
    listen      80;
    # host域名
    server_name example.com www.example.com;
    
    # 设置长连接(可选)
    keepalive_timeout 70;
    
    # 减少点击劫持
    add_header X-Frame-Options DENY;
    # 禁止服务器自动解析资源类型(安全起见,防止文件伪装)
    add_header X-Content-Type-Options nosniff;
    # 防XSS攻击
    add_header X-Xss-Protection 1;
    
    # 默认页面
    index index.html index.htm index.php default.html default.htm default.php;    
    # 网站源码主目录
    root  /home/wwwroot/example.com;
    # 写访问日志
    access_log  /home/wwwlogs/kuaimashi.com.log  main;
    # 文件匹配规则(详解http://seanlook.com/2015/05/17/nginx-location-rewrite/index.html)
    location ~ [^/]\.php(/|$) {
        try_files $uri =404;
        #fastcgi_pass  unix:/tmp/php-cgi.sock;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
        # 静态资源30天过期
        expires      30d;
    }
    location ~ .*\.(js|css)?$ {
        # js, css 12小时过期
        expires      12h;
    }
    location / {
        index index.php;
        if (!-e $request_filename) {
            rewrite ^/(.*)$ /index.php?$1 last;
            break;
        }
    }
}

保存并关闭

在nginx的主配置文件nginx.conf中include引入虚拟主机的配置文件(放在括号内的最下面即可)

 include vhost/*.conf;

配置文件写好了,这时最好先测试文件是否书写正确

nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx -t输出这样表明配置无误,否则需要根据输出进行配置文件检查

在确认虚拟主机文件无误后,让nginx把我们的配置文件加载进来(reload)

nginx -s reload

加载完毕后就可以在浏览器看效果了

================= 虚拟主机介绍完毕 =================

 

后续继续记录HTTPS,静态资源处理,反向代理常见用法

 

文章有不足之处请直接指出,互相学习交流QQ:1485619676

nginx常用配置系列-虚拟主机

标签:页面   需要   pre   div   location   代理   监听   http   root   

原文地址:http://www.cnblogs.com/ieinstein/p/7068796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!