Nginx的安裝和部署


Nginx簡介

Nginx是一款輕量級的Web 服務器/反向代理服務器電子郵件(IMAP/POP3)代理服務器,在BSD-like 協議下發行。其特點是占有內存少並發能力強,事實上nginx的並發能力在同類型的網頁服務器中表現較好,中國大陸使用nginx網站用戶有:百度京東新浪網易騰訊淘寶等。

優勢

Nginx 可以在大多數 Unix Linux OS 上編譯運行,並有 Windows 移植版。 Nginx 的1.20.0穩定版已經於2021年4月20日發布,一般情況下,對於新建站點,建議使用最新穩定版作為生產版本,已有站點的升級急迫性不高。Nginx 的源代碼使用 2-clause BSD-like license
Nginx 是一個很強大的高性能Web反向代理服務,它具有很多非常優越的特性:

  • 在連接高並發的情況下,NginxApache服務不錯的替代品:Nginx在美國是做虛擬主機生意的老板們經常選擇的軟件平台之一。能夠支持高達 50,000 個並發連接數的響應。
  • Nginx作為負載均衡服務:Nginx 既可以在內部直接支持 Rails 和 PHP 程序對外進行服務,也可以支持作為 HTTP代理服務對外進行服務。Nginx采用C進行編寫,不論是系統資源開銷還是CPU使用效率都比 Perlbal 要好很多。
  • 處理靜態文件索引文件以及自動索引,打開文件描述符緩沖
  • 無緩存的反向代理加速,簡單的負載均衡容錯
  • FastCGI,簡單的負載均衡容錯
  • 模塊化的結構。包括 gzipping, byte ranges, chunked responses,以及 SSI-filter 等 filter。如果由 FastCG或其它代理服務器處理單頁中存在的多個 SSI,則這項處理可以並行運行,而不需要相互等待。
  • 支持 SSLTLSSNI
  • Nginx代碼完全用C語言從頭寫成,已經移植到許多體系結構和操作系統,包括:Linux、FreeBSD、Solaris、Mac OS X、AIX以及Microsoft Windows。Nginx有自己的函數庫,並且除了zlib、PCRE和OpenSSL之外,標准模塊只使用系統C庫函數。而且,如果不需要或者考慮到潛在的授權沖突,可以不使用這些第三方庫。
  • 代理服務器。作為郵件代理服務:Nginx 同時也是一個非常優秀的郵件代理服務(最早開發這個產品的目的之一也是作為郵件代理服務器),Last.fm 描述了成功並且美妙的使用經驗。
  • Nginx 是一個安裝非常的簡單、配置文件非常簡潔(還能夠支持perl語法)、Bug非常少的服務。Nginx 啟動特別容易,並且幾乎可以做到7*24不間斷運行,即使運行數個月也不需要重新啟動。你還能夠不間斷服務的情況下進行軟件版本的升級。

使用

下載

官網下載最新穩定版

image-20210511134526594

從源代碼構建

如果需要某些特殊功能,但軟件包和端口不提供這些功能,則也可以從源文件編譯nginx。雖然更靈活,但是這種方法對於初學者來說可能很復雜。有關更多信息,請參見從源代碼構建nginx。

安裝

下載完成后解壓到不含中文(切記!)的目錄

image-20210511134646549

啟動

兩種方法:

  1. 直接雙擊該目錄下的"nginx.exe",即可啟動nginx服務器;

  2. 命令行進入該文件夾,執行start nginx命令,也會啟動nginx服務器。
    使用 Win+R打開運行,輸入cmd,然后按Enter
    首先進入nigix所在的目錄,如下圖所示:

D:
cd Environment/nginx-1.20.0 #這是我解壓的目錄,替換成自己的即可

image-20210511135323876

啟動:start nginx.exe

停止:nginx.exe -s stop

重新加載:nginx.exe -s reload

使用http://localhost:端口查看

那么怎么知道自己的nginx是否啟動成功:打開你的管理器,如在進程中看到兩個nginx說明啟動成功。

image-20210511141124049

打開瀏覽器輸入http://localhost,顯示以下界面即表示啟動成功

image-20210511141246443

反代理Tomcat

反向代理動態頁面

首先用Tomcat啟動一個JavaWeb項目,Tomcat端口號為8080,響應內容如下

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    PrintWriter out = resp.getWriter();

    Cookie[] cookies = req.getCookies();
    if (cookies == null) {
        out.write("First");
    } else {
        out.write("上次時間是:");
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("lastTime")) {
                long l = Long.parseLong(cookies[i].getValue());
                String s = new Date(l).toString();
                out.write(s);
            }

        }
    }
    resp.addCookie(new Cookie("lastTime", System.currentTimeMillis()+""));

}

每次刷新都會動態從Cooki中獲取上次時間,啟動后瀏覽器訪問http://localhost:8080/c1即可查看效果

img

然后編輯Nginx配置文件,新增一個包

upstream tomcatserver {
    server localhost:8080;
}

然后編輯server閉包,修改如下內容

Listen 80;
    server_name localhost;
location / {
    proxy_pass http://tomcatserver;
}

之后啟動Nginx,訪問localhost/c1即可預覽效果

img

則表示正確代理了動態頁面

Nginx的配置

配置文件位於安裝目錄下的/conf/nginx.conf文件

server {
    listen       80; #監聽的端口
    server_name  localhost; #監聽的域名
    #charset koi8-r;
    #access_log  logs/host.access.log  main;
    location / {
		#root html;
		#index index.html index.html;
        proxy_pass http://127.0.0.1:8081; #轉發請求的地址
		proxy_connect_timeout 600;
		proxy_read_timeout 600;
}

Windows下的常用命令

啟動服務:start nginx
退出服務:nginx -s quit
強制關閉服務:nginx -s stop
重載服務:nginx -s reload  (重載服務配置文件,類似於重啟,服務不會中止)
驗證配置文件:nginx -t
使用配置文件:nginx -c "配置文件路徑"
使用幫助:nginx -h

Linux下的安裝

一、安裝編譯工具及庫文件

yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

二、首先要安裝 PCRE

PCRE 作用是讓 Nginx 支持 Rewrite 功能。

1、下載 PCRE 安裝包,下載地址: http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz

cd /usr/local/src/
wget http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz

2、解壓安裝包:

tar zxvf pcre-8.35.tar.gz

3、進入安裝包目錄

cd pcre-8.35

4、編譯安裝

./configure
make && make install

5、查看pcre版本

pcre-config --version

安裝 Nginx

1、下載 Nginx,下載地址:https://nginx.org/en/download.html

cd /usr/local/src/
wget http://nginx.org/download/nginx-1.20.0.tar.gz

2、解壓安裝包

tar zxvf nginx-1.20.0.tar.gz

3、進入安裝包目錄

cd nginx-1.20.0

4、編譯安裝

./configure --prefix=/usr/local/webserver/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/usr/local/src/pcre-8.35
make
make install

到此,nginx安裝完成。


Nginx 配置

nginx.conf說明

#user  nobody;
worker_processes  1; #工作進程:數目。根據硬件調整,通常等於cpu數量或者2倍cpu數量。

#錯誤日志存放路徑
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid; # nginx進程pid存放路徑

events {
    worker_connections  1024; # 工作進程的最大連接數量
}


http {
    include       mime.types; #指定mime類型,由mime.type來定義
    default_type  application/octet-stream;

    # 日志格式設置
    #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  logs/access.log  main; #用log_format指令設置日志格式后,需要用access_log來指定日志文件存放路徑
    				
    sendfile        on; #指定nginx是否調用sendfile函數來輸出文件,對於普通應用,必須設置on。如果用來進行下載等應用磁盤io重負載應用,可設着off,以平衡磁盤與網絡io處理速度,降低系統uptime。
    #tcp_nopush     on; #此選項允許或禁止使用socket的TCP_CORK的選項,此選項僅在sendfile的時候使用
 
    #keepalive_timeout  0;  #keepalive超時時間
    keepalive_timeout  65;
     
    #gzip  on; #開啟gzip壓縮服務
     
    #虛擬主機
    server {
        listen       80;  #配置監聽端口號
        server_name  localhost; #配置訪問域名,域名可以有多個,用空格隔開
     
        #charset koi8-r; #字符集設置
     
        #access_log  logs/host.access.log  main;
     
        location / {
            root   html;
            index  index.html index.htm;
        }
        #錯誤跳轉頁
        #error_page  404              /404.html; 
     
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
     
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
     
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ { #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。
        #    root           html; #根目錄
        #    fastcgi_pass   127.0.0.1:9000; #請求轉向定義的服務器列表
        #    fastcgi_index  index.php; # 如果請求的Fastcgi_index URI是以 / 結束的, 該指令設置的文件會被附加到URI的后面並保存在變量$fastcig_script_name中
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
     
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
     
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;  #監聽端口
    #    server_name  localhost; #域名
     
    #    ssl_certificate      cert.pem; #證書位置
    #    ssl_certificate_key  cert.key; #私鑰位置
     
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m; 
     
    #    ssl_ciphers  HIGH:!aNULL:!MD5; #密碼加密方式
    #    ssl_prefer_server_ciphers  on; # ssl_prefer_server_ciphers  on; #

 

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
}

啟動nginx服務

切換目錄到/usr/local/nginx/sbin下面

image-20210511233708251

啟動nginx命令:

./nginx

查看nginx服務是否啟動成功

ps -ef | grep nginx

image-20210511233800456

訪問站點

從瀏覽器訪問我們配置的站點ip:

image-20210511141246443

Nginx 其他命令

以下包含了 Nginx 常用的幾個命令:

啟動服務:./nginx
退出服務:nginx -s quit
強制關閉服務:nginx -s stop
重載服務:nginx -s reload  (重載服務配置文件,類似於重啟,但服務不會中止)
驗證配置文件:nginx -t
使用配置文件:nginx -c "配置文件路徑"
使用幫助:nginx -h


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM