如何在 Ubuntu 16.04 上更改 Nginx Web 文件位置


在本文中,我們將學習如何移動或更改 Nginx Web 伺服器文件資料夾的位置。預設情況下,Nginx Web 伺服器的預設位置位於 /usr/share/nginx/html,該位置位於 Linux 的預設檔案系統上。通常,這是根據網站要求或客戶端要求來完成的。

先決條件

  • 要完成我們的設定,我們需要以下要求。
  • 安裝了 Ubuntu 16.04,並在機器上具有 sudo 許可權的使用者。
  • 安裝了 Nginx Web 伺服器
  • 已掛載的驅動器或我們想要更改預設文件位置的新文件位置。

將文件根檔案複製到新位置

由於 Nginx 預設文件根位於 /usr/share/nginx/html,如果您已安裝 Nginx 並配置了現有伺服器,則需要檢查位於 /etc/nginx/sites-enabled 的 sites-enabled 資料夾,如果現有伺服器上的位置已更改,我們可以使用以下命令搜尋 sites-enabled 資料夾

$ grep “root” –R /etc/nginx/sites-enabled
/etc/nginx/sites-enabled/default: root /usr/share/nginx/html;
/etc/nginx/sites-enabled/default: # deny access to .htaccess files, if Apache's document root
/etc/nginx/sites-enabled/default:# root /var/www/demosite;

將站點資料移動到新位置

假設我們將預設站點檔案 /var/www/demosite 移動到新建立的卷,該卷位於 /mnt/newdatavolume。

$ sudo rsync –av /usr/share/nginx/html /mnt/newdatavolume

更改 Nginx 的配置檔案

Nginx 允許我們全域性或特定於站點地更改站點的配置,在本演示中,我們使用現有站點將其從預設位置更改為新位置,我們必須使用 grep 命令查詢該位置並更改配置檔案。

$ sudo vi /etc/nginx/sites-enabled/000-default

我們需要查詢“root”行並更新新位置註釋該行並新增新行

root /mnt/newdatavolume

以下是預設 nginx 配置檔案的示例檔案。

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
#root /usr/share/nginx/html;
root /mnt/newdatavolume
index index.html index.htm;
# Make site accessible from https:///
server_name localhost;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
# Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
#location /RequestDenied {
# proxy_pass http://127.0.0.1:8080;
#}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html

重新啟動 Nginx Web 伺服器

配置更改後,我們需要相應地重新啟動 Nginx Web 伺服器以應用更改。首先,我們將檢查配置檔案並重新啟動 Niginx Web 伺服器。

$ sudo nginx –t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ sudo systemctl restart nginx

在上面的文章和設定中,我們學習瞭如何將 Nginx 預設文件根資料夾位置更改為掛載在其他捲上的新位置,我們希望在單個伺服器上管理站點和批次站點資料。

更新於: 2020年1月23日

15K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告