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

<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端口,配置以下:nginx

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

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

 ./nginx -t

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

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”,添加以下节点:url

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

完整配置以下:centos7

server {
    listen 8080;
    server_name localhost;

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

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

从新加载nginx配置文件spa

./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是否须要加上匹配的前缀,在反向代理的使用过程当中,也须要特别注意 

相关文章
相关标签/搜索