nginx部署前端页面总结

140 阅读2分钟

一、mac安装nginx

使用homebrew安装nginx

brew install nginx

通过brew install安装的应用会放在/usr/local/Cellar/目录下

判断是否安装成功

nginx -v

image.png

二、使用

1、启动服务

sudo nginx

默认端口号为8080,默认服务名为localhost,访问localhost:8080 image.png

2、修改配置文件

服务默认指向的文件是/usr/local/var/www/index.html

nginx的配置文件nginx.conf,是在/usr/local/etc/nginx目录下(Mac中/usr/local目录默认在Finder是看不到的,打开Finder,按下command+shift+G,在弹窗中输入/usr/local,或者打开终端中输入cd /usr/local,再输入open .)

image.png

(1)、修改端口号和服务名
 server {
    listen       8080;
    server_name  localhost;
}

修改为

 server {
    listen       9000;
    server_name  127.0.0.1;
}
(2)、修改nginx指向的文件夹

服务默认指向的文件夹是/usr/local/var/www/ 修改配置文件

location / {
    root   /Users/xxx/xxx/public/; #自定义指向文件夹
    index  index.html index.htm; # 默认指向的文件
}
(3)、配置nginx指向的文件夹别名127.0.0.1:9000/test 也会指向制定的文件夹

修改配置文件

location /test { # 这样访问
    alias   /Users/xxx/xxx/public/; #自定义指向文件夹
}

3、判断配置文件是否正确

sudo nginx -t

image.png

4、重新加载配置文件启动服务

修改nginx.conf后必须重新加载配置文件启动服务,网页内容才会改变

sudo nginx -s reload

访问127.0.0.1:9000会发现内容变了

默认会指向index.html文件,也可通过127.0.0.1:9000/[文件名].html访问其他html文件

5、反向代理

例如代理以test开头的请求地址

location /test/ {
    # proxy_set_header Host $http_host;
    # proxy_set_header X-Real-IP $remote_addr;
    # proxy_set_header REMOTE-HOST $remote_addr;
    # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass  http://xxx.xxx.com/test/;
}

6、查看进程

ps -ef|grep nginx

7、停止服务

快速停止命令:sudo nginx -s stop // 不管有没有正在处理的请求,都马上关闭nginx
平稳停止命令:sudo nginx -s quit // 在关闭前,需要把已经接受的连接请求处理完

8、nginx 如何根据不同的路径变量匹配不同的变量.html?

在 Nginx 中,你可以使用正则表达式和路径变量来匹配并加载不同的 .html 文件

server {
    listen 80;
    server_name example.com;

    location ~ ^/(\w+)/?$ {
        root /var/www/html;
        try_files /$1.html =404;
    }
}

在这个配置中,location ~ ^/(\w+)/?$ 使用了正则表达式来匹配 URL 中的路径。(\w+) 会匹配一个或多个字母、数字或下划线,并将其捕获为一个变量。

try_files /$1.html =404; 这行代码的意思是,尝试加载名为 $1.html 的文件,其中 $1 是正则表达式捕获的第一个变量。如果文件不存在,Nginx 会返回 404 错误。

例如,如果你访问 http://example.com/foo,Nginx 就会尝试加载 /var/www/html/foo.html。如果访问 http://example.com/bar,Nginx 就会尝试加载 /var/www/html/bar.html

这样,你就可以根据不同的路径变量来匹配和加载不同的 .html 文件了。