Nginx 使用心得

进击的学霸...大约 2 分钟

今天给大家梳理一下 Nginx 的使用,包括配置、代理等。

现在的项目多是前后端分离的项目,所以我们不必在把前端项目放入后端项目,然后起 Apache 或者 Tomcat 运行后端项目,Apache和Nginx的区别open in new window ,简而言之,现在的 web 项目基本上都是跑在 Nginx 上的,虽然项目部署这类事情不用我们操心,但多了解一点总是没错的。

安装就不赘述了,之前的文章也有提到

别名

通过配置别名的方式来调用nginx

# 设置当前用户的别名
vim ~/.bashrc
# 新增 alias nginx="/service/nginx/sbin/nginx"
source ~/.bashrc

配置

Nginx 的配置默认都在 conf 文件夹下,默认的配置我就不放了,各位安装成功后打开 conf 下的 nginx.conf 就能看到,下面是我改过的配置文件 nginx.conf ,没有用到的一些注释我都删掉了,为了节省篇幅,在 Nginx 的配置中使用 # 来进行注释

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;


    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    # 这行的意思是包含当前目录下的 vhosts 文件夹中的所有以 .conf 结尾的文件,Nginx 支持多配置,这样的方式可以让配置目录更加清晰,也可以将配置都写在这一个文件中,个人建议还是分开写
    include vhosts/*.conf;

    error_page   500 502 503 504  /50x.html;  

}

下面我们使用的主域名以 xxx.com 为例

# /vhosts/xxx_com.conf
server {
        listen       80; # 访问的是 80 端口
        server_name xxx.com; # 访问的域名是 xxx.com
        charset utf-8; # 编码格式为 utf-8
        access_log  logs/xxx_com.access.log; # 成功日志
        error_log   logs/xxx_com.error.log; # 错误日志
		
		location / { # 匹配规则
	    	root   /service/nginx/html/home/; # 站点文件目录
             index  index.html index.htm; # 入口文件格式
        }
}


多个子域名配置

# /vhosts/blog_xxx_com.conf
server {
        listen       80; # 访问的是 80 端口
        server_name blog.xxx.com; # 访问的域名是 blog.xxx.com
        charset utf-8; # 编码格式为 utf-8
        access_log  logs/blog_xxx_com.access.log; # 成功日志
        error_log   logs/blog_xxx_com.error.log; # 错误日志
		
		location / { # 匹配规则
            try_files $uri $uri/ /index.html; # 对单页应用,访问的路由都返回 index.html
	        root   /service/nginx/html/blog/; # 站点文件目录
            index  index.html index.htm; # 入口文件格式
        }
}

上述配置大致意思是,都访问的是本机的 80 端口,但是因为访问的域名不同而使用不同的配置,从而达到多域名配置的效果

代理

。。。

server {
        listen       80;
        server_name blog.xxx.com;
        charset utf-8;
        access_log  logs/blog_xxx_com.access.log;
        error_log   logs/blog_xxx_com.error.log;
		
	location / {
        try_files $uri $uri/ /index.html;
	    root   /service/nginx/html/blog/;
        index  index.html index.htm;
    }

	location ~ /api/ { # 匹配以 api 开头的 url
         proxy_pass  http://127.0.0.1:8090; # 将其代理至本机的 8090 端口(服务端运行在本机的 8090 端口)
	}
}

评论
  • 按正序
  • 按倒序
  • 按热度