current position:Home>Install and configure nginx in Linux Environment

Install and configure nginx in Linux Environment

2022-04-29 08:58:54Er Yue

Linux Environment installation and configuration Nginx

Preface

It's still the project some time ago , The production environment is configured with a domain name nginx, As a result, when I came back from the customer's site, I found that there was no domain name in the test environment , It's not installed , There are some problems during installation , Let's talk about Linux How to install the environment nginx And how to configure the domain name

Install preconditions

Check that... Is installed nginx ( If installed , Skip this step , Just stop

##  Check the default installation path /usr/local/nginx/
cd /usr/local/nginx/sbin
##  perform  
./nginx -V		## If you want to upgrade the version, you can consider uninstalling and then installing 

##  If it is not the default installation path , You can view your installed by viewing the process nginx route 
ps -aux | grep nginx
#  perhaps 
ps -ef | grep nginx
#  perhaps 
whereis nginx

stop it nginx( If it doesn't start , Skip the next step )

#  Mode one : Go to check the default installation path and stop 
/usr/local/nginx/sbin/nginx -s stop
#  Mode two   By looking for nginx The process of killing the process stops 
#  lookup nginx The process of 
ps -ef| grep nginx
#  or 
ps -aux| grep nginx

##  Force to stop nginx
kill -9 pid

 Insert picture description here

Delete completely nginx

Find all names in the root directory, including nginx The file of

find / -name nginx

Global search will often find many related files , But the prefixes are basically the same , Different parts of the back can be used * Instead of , To quickly delete

 rm -rf /usr/local/sbin/nginx
 rm -rf /usr/local/nginx
 rm -rf /usr/src/nginx-1.11.1
 rm -rf /var/spool/mail/nginx

If set Nginx If it starts automatically , The following steps may be required

chkconfig nginx off

rm -rf /etc/init.d/nginx

Installation package download

http://nginx.org/en/download.html
Click here to jump to

It is recommended to download the stable version
 Insert picture description here

The formal installation nginx

install nginx Dependent software libraries

yum install -y gcc openssl openssl-devel zlib zlib-devel pcre-devel

Just downloaded from the official website nginx Upload the package to the server and unzip ( It's recommended to put home Under the directory of )

tar -zxvf file name

Go to the unzipped nginx Under the folder, execute the following commands in sequence

./configure

make

make install

If the following error occurs during installation
src/os/unix/ngx_user.c:26:7: error :‘struct crypt_data’ There is no name ‘current_sal
explain nginx The version of is too low , Or is it linux The version is too high , You can try to lower Linux Version or download a higher version nginx

start-up / stop it / restart nginx

Get into /usr/local/nginx/sbin

#  start-up 
./nginx
#  restart 
./nginx -s reload
#  stop it   Mode one 
./nginx -s stop
#  stop it   Mode two 
pkill -9 nginx 
#  stop it   Mode three   You can refer to the above nginx Process number method 
kill -9  Process number  

Verify that the installation is successful

If there is no change after installation nginx The default is monitor 80 port
Browser access, if nginx If there is no other listening port, you can also access 80 port
Therefore, enter the external network access of the server IP You can verify
 Insert picture description here
 Insert picture description here

nginx Configuration details

Default config To configure

#user nobody;
worker_processes  1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
    
    worker_connections  1024;
}


http {
    
    include       mime.types;
    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;

    sendfile        on;
    #tcp_nopush on;

    #keepalive_timeout 0;
    keepalive_timeout  65;

    #gzip on;

    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$ {
    
        # root html;
        # fastcgi_pass 127.0.0.1:9000;
        # fastcgi_index index.php;
        # 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;

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

}

nginx File structure

...              # Global block 

events {
             #events block 
   ...
}

http      #http block 
{
    
    ...   #http Global block 
    server        #server block 
    {
     
        ...       #server Global block 
        location [PATTERN]   #location block 
        {
    
            ...
        }
        location [PATTERN] 
        {
    
            ...
        }
    }
    server
    {
    
      ...
    }
    ...     #http Global block 
}

1、 Global block : Configuration impact nginx Global instructions . Generally there is operation nginx The user group for the server ,nginx process pid Storage path , Log storage path , Profile import , Allow to generate worker process Number, etc .

2、events block : Configuration impact nginx Server or network connection to user . There is a maximum number of connections per process , Select which event-driven model handles connection requests , Allow multiple network connections at the same time , Open multiple network connection serialization, etc .

3、http block : You can nest multiple server, Configure agent , cache , Configuration of most functions such as log definition and third-party modules . Such as file introduction ,mime-type Definition , Log customization , Whether to use sendfile Transfer files , Connection timeout , Number of single connection requests, etc .

4、server block : Configure the parameters for the virtual host , One http There can be more than one server.

5、location block : Configure the route of the request , And the processing of various pages .

Sample explanation

Let's write a simulation case

###########  Each instruction must have a semicolon end .#################
#user administrator administrators; # Configure users or groups , The default is nobody nobody.
#worker_processes 2; # Number of processes allowed to generate , The default is 1
#pid /nginx/pid/nginx.pid; # Appoint nginx Process running file storage address 
error_log log/error.log debug;  # Make a log path , Level . This setting can be put into a global block ,http block ,server block , This is the level :debug|info|notice|warn|error|crit|alert|emerg
events {
    
    accept_mutex on;   # Set up network connection serialization , To prevent the occurrence of shock , The default is on
    multi_accept on;  # Set whether a process accepts multiple network connections at the same time , The default is off
    #use epoll; # Event driven model ,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    # maximum connection , The default is 512
}
http {
    
    include       mime.types;   # File extension and file type mapping table 
    default_type  application/octet-stream; # Default file type , The default is text/plain
    #access_log off; # Cancel service log  
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; # Custom format 
    access_log log/access.log myFormat;  #combined Default value for log format 
    sendfile on;   # allow sendfile Transfer files by , The default is off, Can be in http block ,server block ,location block .
    sendfile_max_chunk 100k;  # The number of transfers per process call cannot be greater than the set value , The default is 0, There is no upper limit .
    keepalive_timeout 65;  # Connection timeout , The default is 75s, Can be in http,server,location block .

    upstream mysvr {
       
      server 127.0.0.1:6208;
      server 192.168.134.174:9909 backup;  # Hot standby 
    }

	upstream rstsvr {
       
      server 127.0.0.1:9905 weight=10;	# The weight 10  Visit website 30 This service was accessed this time 10 Time 
      server 192.168.134.174:38080 weight=20;  # The weight 20  Visit website 30 This service was accessed this time 20 Time 
    }
    
    error_page 404 https://www.baidu.com; # Error page 
    server {
    
        keepalive_requests 120; # Maximum number of single connection requests .
        listen       4545;   # Listening port   Silent for 80
        server_name  127.0.0.1;   # Monitor address   perhaps   domain name  
        location  ~*^.+$ {
           # Requested url Filter , Regular matching ,~ For case sensitivity ,~* For case insensitive .
           #root path; # root directory 
           #index vv.txt; # Set default page 
           proxy_pass  http://mysvr; # Request turn mysvr  List of defined servers 
           deny 127.0.0.1;  # refuse ip
           allow 192.168.134.176; # Allow the ip 
        } 

		location  ^~/rstsvr {
           # Requested url Filter , Regular matching ,~ For case sensitivity ,~* For case insensitive .
           #root path; # root directory 
           #index vv.txt; # Set default page 
           proxy_pass  http://rstsvr; # Request turn rstsvr  List of defined servers 
           deny 127.0.0.1;  # refuse ip
           allow 192.168.134.176; # Allow the ip 
        } 
    }
}

It's on it nginx Basic configuration , The following points need to be noted
1、 Basic configuration
1. r e m o t e a d d r And remote_addr And remoteaddr And http_x_forwarded_for To record the ip Address ;
2. r e m o t e u s e r : use Come on remember record customer Household End use Household name call ; 3. remote_user : Used to record client user name ; 3. remoteuser use Come on remember record customer Household End use Household name call ;3.time_local : Used to record access time and time zone ;
4. r e q u e s t : use Come on remember record please seek Of u r l And h t t p Association discussion ; 5. request : Used to record requests url And http agreement ; 5. request use Come on remember record please seek Of url And http Association discussion ;5.status : Used to record request status ; Success is 200;
6. b o d y b y t e s s e n t : remember record Hair send to customer Household End writing Pieces of Lord body Inside Rong Big Small ; 7. body_bytes_s ent : Record the size of the body content sent to the client file ; 7. bodybytessent remember record Hair send to customer Household End writing Pieces of Lord body Inside Rong Big Small ;7.http_referer : Used to record the links from that page ;
8.$http_user_agent : Record client browser information ;

2、 Panic group phenomenon
An Internet connection is coming , Multiple sleep processes are woken up by colleagues , But only one process can get a link , This will affect system performance .

3、 Each instruction must have a semicolon end .

Xiao Qi is also groping and adding configuration , There will be specific cases to supplement later

Share one of my favorite words : Every day is a new day , Good luck, of course , But I'd like to be exactly the same . such , When luck comes , You'll be ready . ———— Hemingway 《 The old man and the sea 》

copyright notice
author[Er Yue],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290620416029.html