基于CentOS搭建Nginx 静态网站

系统要求: CentOS 7.2 64 位操作系统

一. 安装 Nginx(在 CentOS 上,可直接使用 yum 来安装 Nginx)

yum install nginx -y

安装完成后,使用 nginx 命令启动 Nginx(如果无法访问,请重试用 nginx -s reload 命令重启 Nginx):

nginx

此时,访问 http://118.89.65.22 可以看到 Nginx 的测试页面

配置静态服务器访问路径

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

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

示例代码:/etc/nginx/nginx.conf

 1 user nginx;
 2 worker_processes auto;
 3 error_log /var/log/nginx/error.log;
 4 pid /run/nginx.pid;
 5 
 6 include /usr/share/nginx/modules/*.conf;
 7 
 8 events {
 9     worker_connections 1024;
10 }
11 
12 http {
13     log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
14                       '$status $body_bytes_sent "$http_referer" '
15                       '"$http_user_agent" "$http_x_forwarded_for"';
16 
17     access_log  /var/log/nginx/access.log  main;
18 
19     sendfile            on;
20     tcp_nopush          on;
21     tcp_nodelay         on;
22     keepalive_timeout   65;
23     types_hash_max_size 2048;
24 
25     include             /etc/nginx/mime.types;
26     default_type        application/octet-stream;
27 
28     include /etc/nginx/conf.d/*.conf;
29 
30     server {
31         listen       80 default_server;
32         listen       [::]:80 default_server;
33         server_name  _;
34         root         /data/www;
35 
36         include /etc/nginx/default.d/*.conf;
37 
38         location / {
39         }
40 
41         error_page 404 /404.html;
42             location = /40x.html {
43         }
44 
45         error_page 500 502 503 504 /50x.html;
46             location = /50x.html {
47         }
48     }
49 }

配置文件将 /data/www/static 作为所有静态资源请求的根路径,如访问: http://118.89.65.22/static/index.js,将会去 /data/www/static/ 目录下去查找 index.js。现在我们需要重启 Nginx 让新的配置生效,如:

nginx -s reload
重启后,现在我们应该已经可以使用我们的静态服务器了,现在让我们新建一个静态文件,查看服务是否运行正常。首先让我们在 /data 目录 下创建 www 目录,如:
mkdir -p /data/www

创建第一个静态文件

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

 1 <!DOCTYPE html>
 2 <html lang="zh">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>第一个静态文件</title>
 6 </head>
 7 <body>
 8 Hello world!
 9 </body>
10 </html>
现在访问 http://118.89.65.22/index.html 应该可以看到页面输出 
Hello world!
 
到此,一个基于 Nginx 的静态服务器就搭建完成了,现在所有放在 /data/www 目录下的的静态资源都可以直接通过域名访问。
posted @ 2018-02-28 11:43  极客先锋  阅读(1283)  评论(0编辑  收藏  举报