An article teaches you configure nginx to learn safety tips

A plurality of domain site
Server {
the listen 80;
server_name ops-coffee.cn b.ops-coffee.cn ;
}

server_name followed by a plurality of domain names can be, among the plurality of domain names separated by spaces

A plurality of service sites
Server {
the listen 80;
server_name a.ops-coffee.cn ;

location / {
    root /home/project/pa;
    index index.html;
}

}

server {
listen 80;
server_name ops-coffee.cn b.ops-coffee.cn;

location / {
    root /home/project/pb;
    index index.html;
}

}

server {
listen 80;
server_name c.ops-coffee.cn;

location / {
    root /home/project/pc;
    index index.html;
}

}

Based Nginx virtual host configuration, Nginx There are three types of web hosting

IP-based virtual hosts: the need for multiple addresses on your server, each site corresponds to a different address, used in this way is relatively small

Host-based virtual ports: Each site corresponds to a different port, when accessed using the ip: port of access can be modified to use a port listen

Name-based virtual hosting: the most widely used way, above example is to use the domain name-based virtual hosting, provided that you have multiple domain names corresponding to each site, server_name can fill in a different domain

Header head is provided
with the following settings can effectively prevent XSS attacks

add_header X-Frame-Options “SAMEORIGIN”;add_header X-XSS-Protection “1; mode=block”;add_header X-Content-Type-Options “nosniff”;

X-Frame-Options: response header indicates whether to allow the browser to load the frame properties and the like, there are arranged three DENY prohibit any page is embedded, only nested SAMEORIGIN this site, ALLOW-FROM allows nested specified address

X-XSS-Protection: Enable XSS filter representation (disable filter to X-XSS-Protection: 0), mode = block XSS attack said that if checks to stop rendering the page

X-Content-Type-Options: response header is used to specify the browser incorrectly specified or unspecified type of real resources Content-Type speculation behavior, nosniff is not allowed any speculation

In a typical request-response, the browser will be resolved according to the type of response Content-Type, but does not specify the type of response or error is specified, the browser will try to enable MIME-sniffing response to guess the type of the resource, which is very dangerous

For example, a .jpg picture file embedded in a malicious executable js code, in the case of open speculation of resource types, the browser will execute embedded js code, there may be unintended consequences

There are also several security configuration on request header Note

Content-Security-Policy: define what resources can load the page,

add_header Content-Security-Policy “default-src ‘self’”;

Top configuration will limit all external resources, can only be loaded from the current domain, where default-src-defined default loading strategy for all types of resources, self allows content from the same source

Strict-Transport-Security: will tell browser with the HTTPS protocol instead of HTTP to access the target site

add_header Strict-Transport-Security “max-age=31536000; includeSubDomains”;

Top configuration means that when the user first accesses will return a field that contains the Strict-Transport-Security response headers, this field tells the browser, in the next 31,536,000 seconds, all current requests are sites use https access protocol, includeSubDomains parameter is optional, meaning that all subdomains will also adopt the same rules

Add nginx account password authentication
Server {
LOCATION / {
auth_basic "Please the passwd & INPUT User";
auth_basic_user_file Key / auth.key;
}
}

A number of services accessed via nginx, but the account itself does not provide authentication feature, you can authbase account password authentication provided by nginx to achieve, you can use the following script to generate account passwords

cat pwd.pl

#!/usr/bin/perl
use strict;

my p w = pw = ARGV[0] ;
print crypt( p w , church, pw)."\n";

Instructions:

perl pwd.pl ops-coffee.cn

opf8BImqCAXww

echo “admin:opf8BImqCAXww” > key/auth.key

nginx open directory listing
when you want to download nginx exists as a file server, nginx need to open the directory listing

server {
location download {
autoindex on;

    autoindex_exact_size off;
    autoindex_localtime on;
}

}

autoindex_exact_size: show the exact size of the file when on (the default) as the unit is byte; instead show off about file size, in KB or MB or GB

autoindex_localtime: time display when the document is turned off (the default) is the GMT time; later changed to on, the time display for the file server time

Txt, etc. is displayed by default when accessing files listed on the contents of the file browser, if you want to download the browser directly, plus the following configuration

if (KaTeX parse error: Can't use function '\.' in math mode at position 25: …ilename ~* ^.*?\̲.̲(txt|pdf|jpg|pn…) {
add_header Content-Disposition ‘attachment’;
}

The default configuration Site
Server {
the listen 80 default;
}

Find top to bottom by default when a service nginx create multiple virtual hosts, if not match the contents of the first virtual host virtual host will be returned, if you want to specify a default site, this site can be the virtual host configuration file on the location of the first virtual host, or listen default configuration on the virtual host this site

IP is not permitted access
Server {
the listen 80 default;
server_name _;

return      404;

}

There may not record or you do not want the domain name server address points to your server, this time will cause some impact on your site, you need prohibit domain name or IP configuration access, we use said top the default rule, traffic will default to 404 go

This method is rude on top, of course, you can also configure all addresses that are not configured 301s directly to your website to visit to, can bring some traffic to your website

server {
rewrite ^/(.*)$ https://ops-coffee.cn/$1 permanent;
}

Buffer overflow attacks
buffer overflow attack is accomplished by writing data to the buffer and beyond the boundaries of the buffer memory and rewriting fragments, limiting the size of the buffer can be effectively prevented

client_body_buffer_size 1K;client_header_buffer_size 1k;client_max_body_size 1k;large_client_header_buffers 2 1k;

client_body_buffer_size: default 8k or 16k, represents a client request body occupied buffer size. If the connection request buffer exceeds a specified value, then the whole or part of the requesting entity attempts to write to a temporary file.

client_header_buffer_size: represents a client request buffer size of the head. In most cases a request header is not greater than 1k, but if you have come from a large cookie wap client it may be greater than 1k, Nginx will assign it a larger buffer, this value can be set inside the large_client_header_buffers

client_max_body_size: represents a client request maximum acceptable size of the body, as it appears in the Content-Length header field of the request, if the request is greater than the specified value, the client will receive a "Request Entity Too Large" (413) errors, usually when uploading files to the server will be limited

large_client_header_buffers represent some relatively large number and size of the buffer request header used, a default buffer size for the operating system paging file size, typically 4k or 8K, a request field not be greater than the buffer size, if the client sends a comparison large head, Nginx returns "request URI too large" (414), the request header field not be greater than the longest one buffer, otherwise the server returns a "Bad request" (400)

At the same time the need to modify the configuration of several timeout

client_body_timeout 10;client_header_timeout 10;keepalive_timeout 5 5;send_timeout 10;

client_body_timeout: indicates the timeout period read request body, and if the connection time exceeds the client without any response, Nginx returns "Request time out" (408) Error

client_header_timeout: reading indicates timeout client request header, if the connection more than this time without any response to the client, Nginx returns "Request time out" (408) Error

keepalive_timeout: The first parameter indicates the timeout long client and the server is connected, over this time, the server will close the connection, the optional second parameter represents a parameter Response header Keep-Alive: timeout = time value of time this value can cause some browsers know when to close the connection to the server without repeatedly shut down, if you do not specify this parameter, nginx will not be sending Keep-Alive Response header information in

send_timeout: representation sent to the client after the timeout response, Timeout refers not enter the state established a complete, finished only two handshakes, if more than this time the client send nothing, nginx will close the connection

Direct verification file returns
LOCATION /XDFyle6tNA.txt = {
default_type text / Plain;
return 200 is 'd6296a84657eb275c05c31b10924f6ea';
}

Many times micro letters and other procedures we need to put a txt file into the project in order to verify ownership of the project, we can modify nginx can be directly on top this way, no real place to put files on the server

nginx arranged upstream the reverse proxy
HTTP {
...
upstream TOMCATS {
Server weight = 192.168.106.176. 1;
Server = weight 192.168.106.177. 1;
}

server {
    location /ops-coffee/ { 
        proxy_pass http://tomcats; 

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

}

Little carelessness may fall into a bar without bar plus proxy_pass trap here in detail under proxy_pass http: // tomcats and proxy_pass HTTP: // TOMCATS / difference:

Although only a / distinction vary but the results determined. The following two cases:

  1. Destination address without uri (proxy_pass HTTP: // TOMCATS ). At this point a new target url, the match uri part will not be modified, it turned out to be what it is.

location /ops-coffee/ {
proxy_pass http://192.168.106.135:8181;
}

http://domain/ops-coffee/ --> http://192.168.106.135:8181/ops-coffee/
http://domain/ops-coffee/action/abc --> http://192.168.106.135:8181/ops-coffee/action/abc

  1. Destination address with uri (proxy_pass HTTP: // TOMCATS /, / is uri), in this case a new target url, uri matching portion will be modified for the uri parameter.

location /ops-coffee/ {
proxy_pass http://192.168.106.135:8181/;
}

http://domain/ops-coffee/ --> http://192.168.106.135:8181
http://domain/ops-coffee/action/abc --> http://192.168.106.135:8181/action/abc

Control the number of concurrent connections
can limit the number of concurrent connections through one IP module ngx_http_limit_conn_module

http {

limit_conn_zone $binary_remote_addr zone=ops:10m;



server {

    listen       80;

    server_name  ops-coffee.cn;

    

    root /home/project/webapp;

    index index.html;



    location / {

        limit_conn ops 10;

    }



    access_log  /tmp/nginx_access.log  main;

}

}

limit_conn_zone: setting holding respective keys (e.g., $ binary_remote_addr is) parameters shared memory space state, zone = Space Name: Size

Calculate the size of the variables, e.g. $ size binary_remote_addr variable of the recording IPV4 address is fixed 4 bytes, while the recording IPV6 address fixed 16 bytes, the storage state occupies 32 or 64 bytes in the 32-bit platform, the 64-bit platform occupy 64 bytes. 1m shared memory space can hold about 32,000 state 32-bit, 64-bit 16000 state

Specifies the maximum number of connections a shared memory space already set (e.g., name of spatial ops), and each of the given key value: limit_conn

The above example represents one time only the same IP connection 10

When there are a plurality of instructions configured limit_conn, all connection limit will take effect

http {

limit_conn_zone $binary_remote_addr zone=ops:10m;

limit_conn_zone $server_name zone=coffee:10m;



server {

    listen       80;

    server_name  ops-coffee.cn;

    

    root /home/project/webapp;

    index index.html;

    

    location / {

        limit_conn ops 10;

        limit_conn coffee 2000;

    }

}

}

The total number of connections connected to the top of the configuration will not only limit a single IP source is 10, but also limit a single virtual server 2000

nginx upstream开启keepalive
upstream tomcat {
server ops-coffee.cn:8080;
keepalive 1024;
}

server {
location / {
proxy_http_version 1.1;
proxy_set_header Connection “”;

    proxy_pass http://tomcat;
}

}

nginx proxy will be used in most cases as a reverse projects, such as access tomcat after nginx, php then after nginx, etc., then we open keepalive between nginx and back-end services can reduce the frequency of consumption of resources to create a TCP connection caused configured as above

keepalive: Specifies each nginxworker maximum number of connections that can be held is 1024, the default is not set, i.e. nginx not in effect as a client keepalive

proxy_http_version 1.1: open keepalive requires HTTP protocol version is HTTP 1.1

proxy_set_header Connection "": For compatibility with the old agreement and prevent http headers have caused Connection close keepalive failure, where the need for timely cleared Connection HTTP header

Picture anti-theft chain
location / images / {

valid_referers none blocked www.ops-coffee.cn ops-coffee.cn;

if ($invalid_referer) {

    return  403;

}

}

valid_referers: Verify referer, wherein none allow referer empty, with no blocked protocol allows requests to access image resources in the images except when two or more outer or www.ops-coffee.cn is only allowed referer ops-coffee.cn, otherwise, it returns 403

Of course you can not conform to the rules referer redirects the request to a default image, such as below this

location /images/ {

valid_referers blocked www.ops-coffee.cn ops-coffee.cn

if ($invalid_referer) {

    rewrite ^/images/.*\.(gif|jpg|jpeg|png)$ /static/qrcode.jpg last;

}

}

404 automatically jump to the Home
Server {
LOCATION / {
error_page = @ 404 OPS-Coffee;
}

location @ops-coffee {
   rewrite  .*  / permanent;
}

}

404 pages site appears not particularly friendly, we can emerge through the top of the configuration after 404 to automatically jump to go home

拒绝User-Agent
if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl) {

return 444;

}

There may be some unscrupulous persons would use wget / curl scanning tools such as our website, we can easily thwarted by disabling the corresponding user-agent

444 state Nginx is rather special, if returned 444 then the client will not receive the information returned from the server, like the website can not connect as

Restriction request method
if ( r e q in e s t m e t h O d !   ( G E T P O S T ) request_method !~ ^(GET|POST) ) {

return 405;

}

$ Request_method can obtain the method of nginx request

Configuration only allows GET \ POST method to access other method returns 405

Add account authentication
server {

location / {

    auth_basic "please input user&passwd";

    auth_basic_user_file key/auth.key;

}

}

Add black and white list
white list configuration

location /admin/ {

allow   192.168.1.0/24;

deny    all;

}

Top indicates that only allow access to the host network segment 192.168.1.0/24, reject all other

Can also be written blacklists banning certain address access, allowing all other such

location /ops-coffee/ {

deny   192.168.1.0/24;

allow    all;

}

More often client requests through layers of agents, we need to be limited by $ http_x_forwarded_for, you can write

set a l l o w f a l s e ; i f ( allow false;if ( http_x_forwarded_for = “211.144.204.2”) { set KaTeX parse error: Expected 'EOF', got '}' at position 13: allow true; }̲if (http_x_forwarded_for ~ “108.2.66.[89]”) { set KaTeX parse error: Expected 'EOF', got '}' at position 13: allow true; }̲if (allow = false) { return 404; }

Open HTTPS
Server {

listen 443;

server_name ops-coffee.cn;



ssl on;

ssl_certificate /etc/nginx/server.crt;

ssl_certificate_key /etc/nginx/server.key;

ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;

ssl_ciphers         HIGH:!aNULL:!MD5;

}

ssl on: Open https

ssl_certificate: path configuration nginx ssl certificate

ssl_certificate_key: nginx ssl certificate configuration path of the key

ssl_protocols: Specifies the client to establish ssl protocol version used when connecting, if not compatible TSLv1, can be removed directly

ssl_ciphers: Specifies the encryption algorithm used by client connections, and then here you can configure a higher security algorithms

Hide the version number
http {

server_tokens off;

}

There is often a version of nginx for security loopholes, hidden nginx version number has become one of the main means of optimized security, of course, the most important is the time to upgrade bug fixes

Author: java Micro Technology
Source: CSDN
Original: https://blog.csdn.net/qq_29556507/article/details/91043440
Copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin blog.csdn.net/PyhtonChen/article/details/94617831