nginx部署静态网站

实验环境

  • 服务器:centos7.5 1核1G
  • Nginx版本:nginx-1.14.2

主题

  1. 部署静态文件
  2. 根据不同url请求路径,定向到不同的系统文件夹

部署静态文件

假设nginx安装在“/usr/local/nginx”目录,创建文件夹"/root/web/html",上传index.html到该目录下,index.html的代码如下:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
<span>Hello Nginx</span>
</body>
</html>

修改"/usr/local/nginx/conf/nginx.conf"文件,在http节点下新增server节点,由于80端口已经被使用,那么就使用8080端口,配置如下:

server {
    listen 8080;
    server_name localhost;
    
    location / {
            root /root/web/html;
    }
}

检测nginx.conf文件的正确性,通过nginx指令

 ./nginx -t

输出如下,说明nginx配置文件正确

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重新加载nginx配置文件

./nginx -s reload;

通过浏览器访问“http://ip:8080,输出:Hello Nginx

根据不同url请求路径,定向到不同的系统文件夹

创建文件夹"/root/web/images", 并在该文件夹下上传一张图片“1.jpg", 将url以/images/为前缀的定向到该文件夹,修改nginx配置文件“/usr/local/nginx/conf/nginx.conf”,添加如下节点:

 location /images/ {
    root /root/web;
 }

完整配置如下:

server {
    listen 8080;
    server_name localhost;

    location / {
            root /root/web/html;
    }

    location /images/ {
            root /root/web;
    }
}

重新加载nginx配置文件

./usr/loca/nginx/sbin/nginx -s reload;

访问http://139.9.50.226:8080/images/1.jpg,显示图片, nginx将该请求映射到"/root/web/images/1.jpg"文件。

特别需要注意:

location /images/ {
    root /root/web;
}

该location的作用是将匹配的url的/images/...部分加在root对应的路径后面,nginx映射到文件系统中。

在使用nginx的过程中,经常将该location配置成:

location /images/ {
    root /root/web/images; //设置路径:/root/web/images/images/
}

特别需要注意nginx是否需要加上匹配的前缀,在反向代理的使用过程中,也需要特别注意 

原文地址:https://www.cnblogs.com/pxset/p/10766875.html