search
HomeOperation and MaintenanceNginxHow to build and configure Nginx service under Ubuntu

1. Nginx

Nginx ("engine x") is a high-performance Web and reverse proxy server developed by Russian programmer Igor Sysoev. It is also an IMAP/POP3/SMTP proxy server.

One of the three major WEB servers: apache, Nginx, lighttpd. Nginx is a good alternative and is more suitable than the Apache server when you need to handle high concurrent connections.

nginx application scenarios

  • Static server. (Picture, video service) Another one is lighttpd. Tens of thousands of concurrent files, html, js, css, flv, jpg, gif, etc.

  • Dynamic service, nginx-fastcgi mode to run PHP, jsp. (PHP concurrency is 500-1500, MySQL concurrency is 300-1500).

  • Reverse proxy, load balancing. If the daily pv is below 2000W, you can directly use nginx as a proxy.

  • Caching Service. Similar to SQUID, VARNISH.

The official website provides three versions:

The Nginx official website provides three types of versions
Mainline version: Mainline is the version that Nginx is currently working on. You can It is said to be a development version
Stable version: The latest stable version, the version recommended for production environments
Legacy versions: The stable version of the legacy old version

How to build and configure Nginx service under Ubuntu

2 , nginx service construction

1. Use apt to install

sudo apt install nginx

2. Location after installation:

  • /usr/sbin/nginx: main program

  • /etc/nginx: Store configuration files

  • /usr/share/nginx: Store static files

  • /var/log/nginx: Store logs

3. Start and verify the effect

service nginx start  # 启动nginx
service nginx reload  # 重新加载nginx配置文件

Enter your IP address in the browser, if Wellcome appears to nginx then the configuration is successful.

The other two commands

nginx -s reopen            # 重启 Nginx
nginx -s stop              # 停止 Nginx

How to build and configure Nginx service under Ubuntu

4. Check the version number:

~$ nginx -v
 nginx version: nginx/1.14.0 (Ubuntu)

3. Introduction to nginx configuration file

How to build and configure Nginx service under Ubuntu

1. nginx file structure

  • Global block: Configure instructions that affect nginx globally. Generally, there is a user group for running the nginx server, nginx process pid storage path, log storage path, configuration file introduction, the number of worker processes allowed to be generated, etc.

  • events block: Configuration affects the nginx server or network connection to the user. There are the maximum number of connections per process, which event-driven model to choose to handle connection requests, whether to allow multiple network connections to be accepted at the same time, enable serialization of multiple network connections, etc.

  • http block: You can nest multiple servers, configure proxies, caches, log definitions and other most functions and configure third-party modules. Such as file introduction, mime-type definition, log customization, whether to use sendfile to transfer files, connection timeout, number of single connection requests, etc.

  • server block: Configure the relevant parameters of the virtual host. There can be multiple servers in one http.

  • #location block: Configure the routing of requests and the processing of various pages.

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

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

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

2. Default configuration

##
# 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. Basic configuration of 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           
        } 
    }
}

4. nginx virtual host configuration

#下面是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;
  }

Verify configuration file:

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

5. nginx global variables

  • In order to record the client’s IP address, you can use $remote_addr and $http_x_forwarded_for

  • $remote_user: used to record the client user name;

  • $time_local: used to record the access time and time zone;

  • $request: used to record the URL and http protocol of the request;

  • $status: used to record the request status; success is 200;

  • $body_bytes_s ent: records the size of the body content of the file sent to the client;

  • $http_referer: used to record the page link accessed from;

  • $http_user_agent: Record relevant information of the client browser;

访问链接是: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

6. Nginx main configuration

1. Static Http server configuration

First of all, Nginx is an HTTP server that can display static files (such as HTML and pictures) on the server to the client through the HTTP protocol.
Configuration:

server {
    listen 80;   # 端口
    server_name localhost  192.168.1.100;   # 域名   
    location / {             # 代表这是项目根目录
        root /usr/share/nginx/www;   # 虚拟目录
    }
}

2. Reverse proxy server configuration

What is a reverse proxy?
The client can directly access a website application server through the HTTP protocol. If the website administrator adds an Nginx in the middle, the client requests Nginx, Nginx requests the application server, and then returns the result to the client. At this time, Nginx is Reverse proxy server.

How to build and configure Nginx service under Ubuntu

Reverse proxy configuration:

server {
    listen 80;
    location / {
        proxy_pass http://192.168.0.112:8080;   # 应用服务器HTTP地址
    }
}

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

3、负载均衡配置

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

How to build and configure Nginx service under Ubuntu

负载均衡配置:

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配置还可以过滤有人恶意将某些域名指向你的主机服务器。

The above is the detailed content of How to build and configure Nginx service under Ubuntu. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
如何在 Ubuntu 和其他 Linux 下安装 IDLE Python IDE如何在 Ubuntu 和其他 Linux 下安装 IDLE Python IDEApr 08, 2023 pm 10:21 PM

IDLE(集成开发学习环境Integrated Development and Learning Environment)是一个 ​​Python IDE​​​,由 Python 语言本身编写,在 Windows 中通常作为 ​​Python 安装​​ 的一部分而安装。它是初学者的理想选择,使用起来很简单。对于那些正在学习 Python 的人,比如学生,它可以作为一个很好的 IDE 来开始使用。语法高亮、智能识别和自动补全等基本功能是这个 IDE 的一些特点。你可以随时在官方 ​​文档​​ 中了

聊聊Ubuntu中怎么切换多个 PHP 版本聊聊Ubuntu中怎么切换多个 PHP 版本Aug 30, 2022 pm 07:37 PM

如何在 Ubuntu 中切换多个 PHP 版本?下面本篇文章给大家介绍一下Ubuntu中切换多个 PHP 版本的方,希望对大家有所帮助!

ubuntu怎么重启nginx服务ubuntu怎么重启nginx服务May 23, 2023 pm 12:22 PM

1.使用快捷键【Ctrl+Alt+T】打开终端命令模式。2.可以通过以下方式重启nginx服务。方法一,在nginx可执行目录sbin下,输入以下命令重启/nginx-sreload#重启方法二,查找当前nginx进程号,然后输入命令:kill-HUP进程号,实现重启nginx服务#ps-ef|grepnginx#查找当前nginx进程号]#kill-TERM132#杀死nginx进程,132为nginx进程号

docker内ubuntu乱码怎么办docker内ubuntu乱码怎么办Nov 04, 2022 pm 12:04 PM

docker内ubuntu乱码的解决办法:1、通过“locale”查看本地使用的语言环境;2、通过“locale -a”命令查看本地支持的语言环境;3、在“/etc/profile”文件的结尾处添加“export LANG=C.UTF-8”;4、重新加载“source /etc/profile”即可。

ubuntu php无法启动服务怎么办ubuntu php无法启动服务怎么办Dec 19, 2022 am 09:46 AM

ubuntu php无法启动服务的解决办法:1、在php-fpm.conf里面设置错误日志;2、执行“/usr/sbin/php-fpm7.4 --fpm-config /etc/php/fpm/php-fpm.conf”命令;3、修改php的配置文件注释即可。

Ubuntu如何删除无用的Linux内核Ubuntu如何删除无用的Linux内核May 14, 2023 pm 09:13 PM

查找无用的镜像首先,您可以检查当前使用的内核,您可以通过命令获得信息:uname-aa.例如,它在我的桌面上显示为:复制代码代码如下:magc@magc-desktop:~$uname-aLinuxmagc-desktop2.6.24-19-RT#1SMPpremptRTThu8月21日02:08336003UTC2008i686GNU/Linux然后通过查看这台机器上所有内核的列表来决定哪些需要删除:运行命令:复制代码代码如下:dpkg-get-selections|greplinux例如,我

ubuntu没有php-fpm怎么办ubuntu没有php-fpm怎么办Feb 03, 2023 am 10:51 AM

ubuntu没有php-fpm的解决办法:1、通过执行“sudo apt-get”命令添加php的源地址;2、查看有没有php7的包;3、通过“sudo apt-get install”命令安装PHP;4、修改配置监听9000端口来处理nginx的请求;5、通过“sudo service php7.2-fpm start”启动“php7.2-fpm”即可。

Ubuntu下Nginx如何安装与配置Ubuntu下Nginx如何安装与配置May 17, 2023 am 11:01 AM

1.nginx介绍nginx是一个非常轻量级的http服务器,nginx,它的发音为“enginex”,是一个高性能的http和反向代理服务器,同时也是一个imap/pop3/smtp代理服务器。2.对php支持目前各种web服务器对php的支持一共有三种:(1)通过web服务器内置的模块来实现,例如apache的mod_php5,类似的apache内置的mod_perl可以对perl支持。(2)通过cgi来实现,这个就好比之前perl的cgi,该种方式的缺点是性能差,因为每次服务器遇到这些脚本

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools