目錄
一、Nginx
nginx應用程式場合
二、nginx服務搭建 
1、使用apt安裝
2、安裝後的位置: 
3、啟動並驗證效果
4、檢視版本號:
三、nginx設定檔介紹
1、nginx 檔案結構
2、預設的設定
3、nginx的基本設定
四、 nginx虛擬主機設定
驗證設定檔:
五、nginx全域變數
3、负载均衡配置
4、虚拟主机配置
首頁 運維 Nginx Ubuntu下如何建置與設定Nginx服務

Ubuntu下如何建置與設定Nginx服務

May 19, 2023 pm 05:47 PM
nginx ubuntu

一、Nginx

Nginx("engine x")是一款是由俄羅斯的程式設計師Igor Sysoev所開發高效能的Web和反向代理伺服器,也是一個IMAP/POP3/SMTP代理伺服器。

三大WEB伺服器:apache, Nginx, lighttpd之一。 Nginx是一種很好的替代品,當需要處理高並發連接時,它比Apache伺服器更適合。

nginx應用程式場合

  • 靜態伺服器。 (圖片,視訊服務)另一個是lighttpd。並發幾萬,html,js,css,flv,jpg,gif等。

  • 動態服務,nginx——fastcgi 的方式運行PHP,jsp。 (PHP並發在500-1500,MySQL 並發在300-1500)。

  • 反向代理,負載平衡。日pv2000W以下,都可以直接用nginx做代理。

  • 快取服務。類似 SQUID,VARNISH。

官網提供三種版本:

Nginx官網提供了三種類型的版本 
Mainline version:Mainline 是Nginx 目前主力在做的版本,可以說是開發版 
Stable version:最新穩定版,在生產環境上建議使用的版本 
Legacy versions:遺留的舊版的穩定版

Ubuntu下如何建置與設定Nginx服務

二、nginx服務搭建 

1、使用apt安裝

sudo apt install nginx
登入後複製

2、安裝後的位置: 

  • /usr/sbin/nginx:主程序

  • /etc/nginx:存放設定檔

  • #/usr/share/nginx:存放靜態檔案

  • #/var/log/nginx:存放日誌

3、啟動並驗證效果

service nginx start  # 启动nginx
service nginx reload  # 重新加载nginx配置文件
登入後複製

在瀏覽器輸入你的ip位址,如果出現Wellcome to nginx 那麼就是設定成功。

另外兩個指令

nginx -s reopen            # 重启 Nginx
nginx -s stop              # 停止 Nginx
登入後複製

Ubuntu下如何建置與設定Nginx服務

4、檢視版本號:

~$ nginx -v
 nginx version: nginx/1.14.0 (Ubuntu)
登入後複製

三、nginx設定檔介紹

Ubuntu下如何建置與設定Nginx服務

1、nginx 檔案結構

  • #全域區塊:設定影響nginx全域的指令。一般有運行nginx伺服器的使用者群組,nginx進程pid存放路徑,日誌存放路徑,設定檔引入,允許產生worker process數等。

  • events區塊:配置影響nginx伺服器或與使用者的網路連線。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網路連接序列化等。

  • http區塊:可以嵌套多個server,配置代理,緩存,日誌定義等絕大多數功能和第三方模組的配置。如文件引入,mime-type定義,日誌自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。

  • server區塊:設定虛擬主機的相關參數,一個http中可以有多個server。

  • location區塊:設定請求的路由,以及各種頁面的處理情況。

...              # 全局块。配置影响nginx全局的指令。

events {         # events块。配置影响nginx服务器或与用户的网络连接。
   ...
}

http      # http块。可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。
{
    ...   # http全局块
    server        # server块。配置虚拟主机的相关参数,一个http中可以有多个server。 
    { 
        ...       # server全局块
        location [PATTERN]   # location块。配置请求的路由,以及各种页面的处理情况。
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     # http全局块
}
登入後複製

2、預設的設定

##
# 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.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf;

    root /var/www/html;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
    }

    # pass PHP scripts to FastCGI server
    #
    #location ~ \.php$ {
    #    include snippets/fastcgi-php.conf;
    #
    #    # With php-fpm (or other unix sockets):
    #    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    #    # With php-cgi (or other tcp sockets):
    #    fastcgi_pass 127.0.0.1:9000;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny all;
    #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#    listen 80;
#    listen [::]:80;
#
#    server_name example.com;
#
#    root /var/www/example.com;
#    index index.html;
#
#    location / {
#        try_files $uri $uri/ =404;
#    }
#}
登入後複製

3、nginx的基本設定

########### 每个指令必须有分号结束。#################
#user administrator administrators;  #配置用户或者组,默认为nobody nobody。
#worker_processes 2;  #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大连接数,默认为512
}
http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    #access_log off; #取消服务日志    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
    access_log log/access.log myFormat;  #combined为日志格式的默认值
    sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #热备
    }
    error_page 404 https://www.baidu.com; #错误页
    server {
        keepalive_requests 120; #单连接请求上限次数。
        listen       80;   #监听端口
        server_name  127.0.0.1;   #监听地址       
        location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
           #root path;  #根目录
           #index vv.txt;  #设置默认页
           proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
           deny 127.0.0.1;  #拒绝的ip
           allow 172.18.5.54; #允许的ip           
        } 
    }
}
登入後複製

四、 nginx虛擬主機設定

#
#下面是server虚拟主机的配置段
 server
  {
    listen 80;#监听端口
    server_name localhost;#域名
    index index.html index.htm index.php;
    root /usr/local/webserver/nginx/html;#站点目录
      location ~ .*\.(php|php5)?$
    {
      #fastcgi_pass unix:/tmp/php-cgi.sock;
      fastcgi_pass 127.0.0.1:9000;
      fastcgi_index index.php;
      include fastcgi.conf;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$
    {
      expires 30d;
    #access_log off;
    }
    location ~ .*\.(js|css)?$
    {
      expires 15d;
     #access_log off;
    }
    access_log off;
  }
登入後複製

驗證設定檔:

root@ubuntu: nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
登入後複製

五、nginx全域變數

  • 為了記錄客戶端的IP位址,可以使用$remote_addr和$http_x_forwarded_for

  • #$remote_user :用來記錄客戶端使用者名稱;

  • #$time_local :用來記錄存取時間與時區;

  • #$request : 用來記錄請求的url與http協定;

  • $status :用來記錄請求狀態;成功是200;



#$body_bytes_s ent :記錄傳送給客戶端檔案主體內容大小;Ubuntu下如何建置與設定Nginx服務

$http_referer :用來記錄從該頁面連結造訪過來的;########## ###$http_user_agent :記錄客戶端瀏覽器的相關資訊;#########
访问链接是:http://localhost:88/test1/test.php 
网站路径是:/var/www/html

$host:localhost
$server_port:88
$request_uri:<a href="http://localhost:88/test1/test.php" rel="external nofollow"   target="_blank">http:</a>//localhost:88/test1/test.php
$document_uri:/test1/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test.php
登入後複製
###六、Nginx主要設定######1、靜態Http伺服器設定##### #首先,Nginx是一個HTTP伺服器,可以將伺服器上的靜態檔案(如HTML、圖片)透過HTTP協定展現給客戶端。 ###設定:###
server {
    listen 80;   # 端口
    server_name localhost  192.168.1.100;   # 域名   
    location / {             # 代表这是项目根目录
        root /usr/share/nginx/www;   # 虚拟目录
    }
}
登入後複製
###2、反向代理伺服器設定######什麼是反向代理? ###客戶端本來可以直接透過HTTP協定存取某網站應用程式伺服器,如果網站管理員在中間加上一個Nginx,客戶端請求Nginx,Nginx請求應用程式伺服器,然後將結果傳回給客戶端,此時Nginx就是反向代理伺服器。 ###############反向代理程式設定:###
server {
    listen 80;
    location / {
        proxy_pass http://192.168.0.112:8080;   # 应用服务器HTTP地址
    }
}
登入後複製

既然服务器可以直接HTTP访问,为什么要在中间加上一个反向代理,不是多此一举吗?反向代理有什么作用?继续往下看,下面的负载均衡、虚拟主机,都基于反向代理实现,当然反向代理的功能也不仅仅是这些。

3、负载均衡配置

当网站访问量非常大,也摊上事儿了。因为网站越来越慢,一台服务器已经不够用了。因此,可以将同一应用部署在多台服务器上,以将众多用户请求分配至多台机器进行处理。即使其中一台服务器故障,只要其他服务器正常运行,用户仍然可以正常使用,这是多台服务器带来的好处。Nginx可以通过反向代理来实现负载均衡。

Ubuntu下如何建置與設定Nginx服務

负载均衡配置:

upstream myapp {
    server 192.168.0.111:8080;   # 应用服务器1
    server 192.168.0.112:8080;   # 应用服务器2
}
server {
    listen 80;
    location / {
        proxy_pass http://myweb;
    }
}
登入後複製

4、虚拟主机配置

有的网站访问量大,需要负载均衡。然而并不是所有网站都如此出色,有的网站,由于访问量太小,需要节省成本,将多个网站部署在同一台服务器上。
例如将www.aaa.com和www.bbb.com两个网站部署在同一台服务器上,两个域名解析到同一个IP地址,但是用户通过两个域名却可以打开两个完全不同的网站,互相不影响,就像访问两个服务器一样,所以叫两个虚拟主机。

虚拟主机配置:

server {
    listen 80 default_server;
    server_name _;
    return 444;   # 过滤其他域名的请求,返回444状态码
}
server {
    listen 80;
    server_name www.aaa.com;   # www.aaa.com域名
    location / {
        proxy_pass http://localhost:8080;   # 对应端口号8080
    }
}
server {
    listen 80;
    server_name www.bbb.com;   # www.bbb.com域名
    location / {
        proxy_pass http://localhost:8081;   # 对应端口号8081
    }
}
登入後複製

在服务器8080和8081分别开了一个应用,客户端通过不同的域名访问,根据server_name可以反向代理到对应的应用服务器。

虚拟主机的原理是通过HTTP请求头中的Host是否匹配server_name来实现的,有兴趣的同学可以研究一下HTTP协议。

另外,server_name配置还可以过滤有人恶意将某些域名指向你的主机服务器。

以上是Ubuntu下如何建置與設定Nginx服務的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1662
14
CakePHP 教程
1418
52
Laravel 教程
1311
25
PHP教程
1261
29
C# 教程
1234
24
nginx在windows中怎麼配置 nginx在windows中怎麼配置 Apr 14, 2025 pm 12:57 PM

如何在 Windows 中配置 Nginx?安裝 Nginx 並創建虛擬主機配置。修改主配置文件並包含虛擬主機配置。啟動或重新加載 Nginx。測試配置並查看網站。選擇性啟用 SSL 並配置 SSL 證書。選擇性設置防火牆允許 80 和 443 端口流量。

docker怎麼啟動容器 docker怎麼啟動容器 Apr 15, 2025 pm 12:27 PM

Docker 容器啟動步驟:拉取容器鏡像:運行 "docker pull [鏡像名稱]"。創建容器:使用 "docker create [選項] [鏡像名稱] [命令和參數]"。啟動容器:執行 "docker start [容器名稱或 ID]"。檢查容器狀態:通過 "docker ps" 驗證容器是否正在運行。

docker容器名稱怎麼查 docker容器名稱怎麼查 Apr 15, 2025 pm 12:21 PM

可以通過以下步驟查詢 Docker 容器名稱:列出所有容器(docker ps)。篩選容器列表(使用 grep 命令)。獲取容器名稱(位於 "NAMES" 列中)。

怎麼查看nginx是否啟動 怎麼查看nginx是否啟動 Apr 14, 2025 pm 01:03 PM

確認 Nginx 是否啟動的方法:1. 使用命令行:systemctl status nginx(Linux/Unix)、netstat -ano | findstr 80(Windows);2. 檢查端口 80 是否開放;3. 查看系統日誌中 Nginx 啟動消息;4. 使用第三方工具,如 Nagios、Zabbix、Icinga。

docker怎麼創建容器 docker怎麼創建容器 Apr 15, 2025 pm 12:18 PM

在 Docker 中創建容器: 1. 拉取鏡像: docker pull [鏡像名] 2. 創建容器: docker run [選項] [鏡像名] [命令] 3. 啟動容器: docker start [容器名]

nginx怎麼查版本 nginx怎麼查版本 Apr 14, 2025 am 11:57 AM

可以查詢 Nginx 版本的方法有:使用 nginx -v 命令;查看 nginx.conf 文件中的 version 指令;打開 Nginx 錯誤頁,查看頁面的標題。

nginx怎麼配置雲服務器域名 nginx怎麼配置雲服務器域名 Apr 14, 2025 pm 12:18 PM

在雲服務器上配置 Nginx 域名的方法:創建 A 記錄,指向雲服務器的公共 IP 地址。在 Nginx 配置文件中添加虛擬主機塊,指定偵聽端口、域名和網站根目錄。重啟 Nginx 以應用更改。訪問域名測試配置。其他注意事項:安裝 SSL 證書啟用 HTTPS、確保防火牆允許 80 端口流量、等待 DNS 解析生效。

nginx服務器掛了怎麼辦 nginx服務器掛了怎麼辦 Apr 14, 2025 am 11:42 AM

當 Nginx 服務器宕機時,可執行以下故障排除步驟:檢查 nginx 進程是否正在運行。查看錯誤日誌以獲取錯誤消息。檢查 nginx 配置語法正確性。確保 nginx 具有訪問文件所需的權限。檢查文件描述符打開限制。確認 nginx 正在偵聽正確的端口。添加防火牆規則以允許nginx流量。檢查反向代理設置,包括後端服務器可用性。如需進一步幫助,請聯繫技術支持。

See all articles