“Nginx is a lightweight HTTP server with an event-driven asynchronous non-blocking processing framework that provides excellent IO performance and is often used for server-side reverse proxies and load balancing.”
Ok, I admit I don’t quite understand the official phrase, but there are two key words to remember here, reverse proxy and load balancing, which are the best features of Nginx and can be done with a simple configuration. For those of us who are not professional operation and maintenance, the simplicity of Nginx is very friendly. Let’s start to learn the basic configuration of Nginx, so that we can quickly get started using Nginx.
First, environmental preparation
Here I personally recommend you to use ali Cloud ECS cloud server, because it is more convenient, can be operated anytime and anywhere, do not need to install their own virtual machine what so troublesome. If you are still in school or a fresh graduate, there is a student discount on Ali Cloud, you can buy it after certification, less than 10 yuan a month, it can be said that it is quite a bargain. Post link: Ali cloud server student discount edition… The following is a CentOS7.3 64-bit operating system for configuration, about the Linux command line here only to some basic, encountered do not understand we can baidu, here is no longer redundant.
Install the necessary dependencies to facilitate subsequent operations
yum -y install gcc gcc-c++ autoconf pcre-devel make automake
yum -y install wget httpd-tools vim
Copy the code
To install Nginx, enter:
vim /etc/yum.repos.d/nginx.repo
Copy the code
Then copy the yum source from the official website to the file (press I to enter the state, then press Esc and :wq to save and exit)
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1
Copy the code
You need to change the corresponding operating system and version number after copying. For example, change CenteOs7 to the following
baseurl=http://nginx.org/packages/centos/7/$basearch/
Copy the code
Start the installation
yum install nginx
Copy the code
After the installation is complete, run the nginx -v command to check the version number. If the following message is displayed, the installation is successful:
Ali Cloud security group configuration:
- Open your Ali Cloud console and enter the ECS instance;
- Click More after the instance, move to Network and Security Groups, and click Security Group Configuration
- Click add Security Group configuration in the upper right corner and add the following configuration:
Nginx basic configuration file
Go to the nginx directory and open the nginx.conf configuration file using vim
cd /etc/nginx
vim nginx.conf
Copy the code
Here is what each configuration means
# define users and user groups to run Nginx
user nginx;
# Number of nginx processes. It is recommended that the value be set to the total number of CPU cores
worker_processes 1;
Error log store directory and type
error_log /var/log/nginx/error.log warn;
# process file
pid /var/run/nginx.pid;
events {
worker_connections 1024; # Maximum number of connections per process (maximum number of connections = number of connections * number of processes)
}
Configure the HTTP server
http {
include /etc/nginx/mime.types; File extension and type mapping table
default_type application/octet-stream; The default file type
Set the log format
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 /var/log/nginx/access.log main; #nginx access log location
sendfile on; Sendfile specifies whether nginx calls sendFile to output files. For common applications, set it to on.
If it is used for heavy disk I/O applications such as downloads, you can set it to off to balance disk and network I/O processing speed and reduce system load. Note: Change this to off if the image does not display properly.
#tcp_nopush on; Prevent network congestion
keepalive_timeout 65; # Long connection timeout, in seconds
#gzip on; Enable gzip compression
include /etc/nginx/conf.d/*.conf; Conf files in the conf. D folder will be included in the nginx configuration
Copy the code
Conf Go to conf.d and enter vim default.conf to view the configuration file
server {
listen 80; Configure the listening port
server_name localhost; # configure domain name
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html; The default startup directory of the service represents the folder to which access to the root directory is redirected
index index.html index.htm; Access files by default
}
#error_page 404 /404.html; # used to configure 404 pages
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html; Error status code corresponding to the display page
The content after # location can be reged-matched
location = /50x.html {
root /usr/share/nginx/html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#location ~ \.php$ {
# proxy_pass http://127.0.0.1; The address of the proxy
#}
# 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;
#}
}
Copy the code
Nginx service startup, shutdown, and reload
Start the
nginx
Copy the code
Shut down
nginx -s quit Stop the process until it finishes its current work
nginx -s stop # Stop the process immediately, whether it is working or not
killall nginx # Kill the process. This command can be used when the previous two operations fail
Copy the code
Reload the configuration file
Reload every time an Nginx configuration item is modified
nginx -s reload
Copy the code
Viewing port Numbers
By default, nginx will listen on port 80 to provide HTTP services. If the startup fails, the port will be checked to see if it is used:
netstat -tlnp
Copy the code
4. Error page customization and access control
Custom error pages
When there is error page access, we usually need to through the different error types to return different error page, the user, allows the user to return to other pages, to achieve a better user experience, the forecast error and take corresponding measures is also we must be able to develop ideas, Nginx can be very convenient for us to do this.
Open the default.conf folder in the conf.d folder of the nginx directory, and you can see the following two configuration items
error_page 500 502 503 504 /50x.html; # indicates that multiple error types point to the same page
error_page 404 /404_error.html; Specify a separate return page for an error type
Copy the code
By configuring the error type of error_page and the corresponding HTML file path, we can return the corresponding error message interface to the user.
Access Settings
As the name implies, that is to control user access, for example, we usually do not want users to access some pages, although users do not know our file path, but can not rule out some misoperations or malicious operations, so in order to improve the security of the application, we must set some permissions for users.
Location / {allow 47.102.143.128;Set the user Ip to allow accessAllow 192.168.1.16; deny all;Set access denied to all users
If the Ip addresses are not matched, access is not allowed. If the Ip addresses are not matched, access is forbidden
# however, if deny all is set above, the following rules will not be matched, even if allow is set below
Allow all
}
# specify access permissions for some files or paths
location =/public { # "=" indicates an exact match
allow all;
}
location =/private {
deny all;
}
location ~\.php$ { Use a regular expression to prevent access to files that end in PHP
deny all;
}
Copy the code
Five, virtual host configuration
First we have to understand what is the virtual host?
Virtual hosting (English: Virtual hosting) or shared Web hosting (shared Web hosting), also known as virtual server, is a single host or host group, to achieve multi-domain services, can run multiple websites or services technology. Virtual host between completely independent, and can be managed by the user, virtual does not mean that there is no existence, but refers to the space is extended by the entity of the server, its hardware system can be based on the server group, or a single server.
We can easy to understand it as from the primary partition of sub server above, and also have the function that provides a web service, means we can only use one server can deploy multiple sites, so we can put the project, we usually do the demo, resume or only one server can deploy all online, We can show our skills as much as possible during the interview.
Configure virtual hosts based on port numbers
Nginx distinguishes between different sites based on how many port numbers it listens on.
(Check the security group rules of the ESC server to allow access to your configured port number, otherwise the port will not be accessible.)
We can create a new self-configuration file in the conf.d folder with the.conf end
server{
listen 8008;
server_name localhost;
root /usr/share/nginx/html/server8008;
index index.html;
}
server{
listen 8009;
server_name localhost;
root /usr/share/nginx/html/server8009;
index index.html;
}
Copy the code
Port 8008, port 8009 and port 80 are all running under nginx-s reload and netstat -tlnp. It means we can deploy whatever you want to show on these three different ports.
Set up a virtual host using a domain name
Here we need to register a domain name first, if you want to show your work to others, I highly recommend you to register a domain name, after all, no one will remember an IP address. Then we first resolve the domain name (domain name resolution to a series of authentication and record, otherwise it may fail to resolve, these to ali Cloud to operate)
server{
listen 80;
server_name xxx.xxx.com; # Here is the domain name you resolved
location / {
root /usr/share/nginx/html/server8008;
index index.html index.html;
}
}
server{
listen 80;
server_name xxx2.xxx.com; # Here is another domain you resolvedlocation / { root /usr/share/nginx/html/server8009; index index.html index.html; }}Copy the code
After the modification is complete, reload the configuration and you can access the two domain names separately.
Reverse proxy and load balancing
What is a reverse proxy? Take a look at a picture:
As you can see, when a user accesses an Nginx proxy server, Nginx forwards the request to another server, which server is completely controlled by our Nginx
Benefits of reverse proxy:
- Improved security: Through nginx reverse proxy, users do not know which real server they are accessing, which is a good way to protect our server;
- Load balancing: As you can see from the figure above, the reverse proxy can distribute user requests to multiple servers. This allows us to provide different services across multiple sub-servers, reducing the load balancing effect on our primary server.
A simple implementation of reverse proxy
server{ listen 80; server_name xxx.xxx.com; Location / {proxy_pass 192.168.1.16The IP or domain name of the proxy}}Copy the code
After this configuration, when users access XXX.xxx.com, nginx will proxy us to 192.168.1.16, which implements a reverse proxy.
Perform other configurations for the reverse proxy
proxy_set_header
: Changes the request header information from the client before sending the client request to the back-end server.proxy_connect_timeout
: Sets the timeout period for Nginx to attempt to establish a connection with the backend proxy server.proxy_read_timeout
: Configures the timeout period for Nginx to wait for a read request from a back-end server group.proxy_send_timeout
: Sets the timeout period for Nginx to wait for a write request from a back-end server group.proxy_redirect
: used to modify Location and Refresh in the response header returned by the back-end server.
Nginx identifies different devices
Nginx can do the same for you by visiting taobao or JD.com and opening developer tools in Chrome. When you refresh on your mobile device, it will show you a mobile page.
Via Nginx built-in variables$http_user_agent
Gets the userAgent of the requesting client
server{
listen 80;
server_name xxx.xxx.com;
location / {
root /usr/share/nginx/pc; Access to render PC site under normal state
if ($http_user_agent~ *'(Android|webOS|iPhone|iPod|BlackBerry)') { Get user device information
root /usr/share/nginx/mobile; Render mobile sites when users visit for mobile devices} index index.html; }}Copy the code
At the end
This is the introduction to Nginx configuration items!
These configurations are totally out of the question when it comes to deploying our own live projects or personal blogs, so as a front-end developer, get your hands on them.