搭建 Nginx 静态网站

搭建HTTP静态服务器环境

搭建静态网站,首先需要部署环境。下面的步骤,将告诉大家如何在服务器上通过 Nginx 部署 HTTP 静态服务。

安装 Nginx

在 CentOS 上,可直接使用 yum 来安装 Nginx

yum install nginx -y

在 Ubuntu 上则可以通过 apt-get 源

$ apt-get install nginx

安装完成后,使用命令启动 Nginx

nginx

此时,访问 http://你的域名/,就可以看到 Nginx 的测试页面。

备注:如果无法访问,请重试用 nginx -s reload 命令重启 Nginx。

配置静态服务器访问路径

外网用户访问服务器的 Web 服务由 Nginx 提供,Nginx 需要配置静态资源的路径信息才能通过 url 正确访问到服务器上的静态资源。

简单地配置 Nginx 的配置文件,以便在启动 Nginx 时去启用这些配置。而本文的重点也是于此。

Nginx 的配置系统由一个主配置文件和其他一些辅助的配置文件构成。这些配置文件均是纯文本文件,一般地,我们只需要配置主配置文件就行了。例如在我的服务器上是在:/etc/nginx/nginx.conf

打开 Nginx 的默认配置文件 /etc/nginx/nginx.conf ,修改 Nginx 配置,将默认的
root /usr/share/nginx/html;
修改为:
root /data/www;

nginx.conf 中的配置信息,根据其逻辑上的意义,对它们进行了分类,也就是分成了多个作用域,或者称之为配置指令上下文。不同的作用域含有一个或者多个配置项。

其中每个配置项由配置指令和指令参数构成,形成一个键值对,# 后面地为注释,理解起来也非常容易。

一般配置文件的结构和通用配置如下:

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /data/www;

        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

}

配置文件将 /data/www/static 作为所有静态资源请求的根路径,如访问: http://<您的域名>/static/index.js,将会去 /data/www/static/ 目录下去查找 index.js。

现在我们需要重启 Nginx 让新的配置生效,如:

nginx -s reload

重启后,现在我们应该已经可以使用我们的静态服务器了,现在让我们新建一个静态文件,查看服务是否运行正常。

创建第一个静态文件

首先让我们在 /data 目录下创建 www 目录,如:

mkdir -p /data/www

在 /data/www 目录下创建我们的第一个静态文件 index.html

示例代码:/data/www/index.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Welcome</title>
</head>
<body>
Hello, Welcome to Wan's world!
</body>
</html>

现在访问 http://<您的域名>/index.html 应该可以看到页面输出 [Hello, Welcome to Wan's world!]

到此,一个基于 Nginx 的静态服务器就搭建完成了,现在所有放在 /data/www 目录下的的静态资源都可以直接通过域名访问。

后记:用阿里云服务器的同学们要注意了,我用阿里云的服务器忙活了一下午重装了系统盘好几次还是不能正常访问域名,最后知道真相的我眼泪掉下来了。

参考文章:https://www.jb51.net/article/141340.htm
阿里云解决方案:https://blog.csdn.net/LJFPHP/article/details/78670459

作者: Hugh

Welcome to Wan's world~