Nginx入门------(一)

211 阅读2分钟

windows上安装

下载: nginx.org/en/download… 解压:

常用命令

start nginx 		: 启动nginx
nginx -t			: 检查nginx 当前使用的配置文件语法是否正确
nginx -s reload 	:重新加载配置文件
nginx -s quit		:退出---完成且有序的退出
nginx -s stop		:快速停止

管理员cmd 进入上图目录
start nginx 启动nginx,logs文件夹中出现以下三个文件表示启动成功。 没有nginx.pid 说明没有启动成功。
浏览器访问:localhost, 也可以自定义域名 修改nginx.conf 文件为以下内容

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    server {
        listen       9999;
        server_name  localhost;
        location /edu/ {
            proxy_pass http://localhost:8001;
        }
		location /vod/ {
            proxy_pass http://localhost:8002;
        }
    }
}

nginx -s reload 重新加载配置文件
以上配置监听了9999端口,我本地配置了两个tomcat,分别对应8001和8002端口,在对应tomcat下添加应用。 浏览器:http://localhost:9999/edu/
浏览器:http://localhost:9999/vod/
至此,简单实现了使用反向代理不同的服务

采坑

启动nginx失败

原因1:点击nginx.exe启动

点击ngingx.exe有可能会启动失败,至少我的电脑上是这样, 推荐使用 start nginx 命令进行启动

原因2:80端口被占用

cmd 中输入指令 netsh http show servicestate ;找到进程id 任务管理器中关闭对应的进程

404

配置文件与上面相同, 但是在tomcat,webapps目录下没有/edu/index.html,和/vod/index.html 这种404可以在webapps目录中添加edu/index.html;也可以在webapps中添加/ROOT/edu/index.html

理解误区

location /edu/ {
            proxy_pass http://localhost:8001;
        }

location的定义被理解为: 访问http://localhost:9999/edu/ 被代理访问 http://localhost:8001/,实际上是访问 http://localhost:8001/edu/
若要实现 http://localhost:9999/edu/ 被代理访问 http://localhost:8001/ 需要修改配置文件

server {
        listen       9999;
        server_name  localhost;
        location /edu/ {
            proxy_pass http://localhost:8001/;
			
        }
		
		location /vod/ {
            proxy_pass http://localhost:8002/;
			
        }
    }

多加了一个斜杠,访问的页面就不一样了,而是下面的位置