搭建Nginx靜態網站-騰訊雲
搭建靜態網站
搭建Http靜態伺服器環境
任務時間:15min ~ 30min
搭建靜態網站,首先需要部署環境。下面的步驟,將告訴大家如何在伺服器上通過 Nginx 部署 HTTP 靜態服務。
安裝 Nginx
在 CentOS 上,可直接使用 yum
來安裝 Nginx
yum install nginx -y
安裝完成後,使用 nginx
命令啟動 Nginx:
nginx
此時,訪問 http://<您的域名> 可以看到 Nginx 的測試頁面 [?]
如果無法訪問,請重試用
nginx -s reload
命令重啟 Nginx
配置靜態伺服器訪問路徑
外網使用者訪問伺服器的 Web 服務由 Nginx 提供,Nginx 需要配置靜態資源的路徑資訊才能通過 url 正確訪問到伺服器上的靜態資源。
開啟 Nginx 的預設配置檔案 /etc/nginx/nginx.conf ,修改 Nginx 配置,將預設的 root
/usr/share/nginx/html;
修改為: root /data/www;
,如下:
示例程式碼:/etc/nginx/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>第一個靜態檔案</title>
</head>
<body>
Hello world!
</body>
</html>
到此,一個基於 Nginx 的靜態伺服器就搭建完成了,現在所有放在 /data/www 目錄下的的靜態資源都可以直接通過域名訪問。
如果無顯示,請重新整理瀏覽器頁面
完成實驗
恭喜!您已經成功完成了 搭建Http靜態伺服器環境 的實驗任務。