Nginx configuration and optimization of common safety

A site configuration multiple domain names

server {
    listen       80; server_name demo.ct99.cn demo1.ct99.cn; }

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

A service configuration multiple sites

server {
    listen       80; server_name demo.ct99.cn; location / { root /home/project/pa; index index.html; } } server { listen 80; server_name demo1.ct99.cn; location / { root /home/project/pb; index index.html; } } server { listen 80; server_name demo2.ct99.cn; location / { root /home/project/pc; index index.html; } }

Based Nginx virtual host configuration, Nginx There are three types of virtual hosts
IP-based virtual hosts: the need to have multiple addresses on your server, each site corresponds to a different address, is relatively small in this way using
port-based virtual hosts : each site corresponds to a different port, when accessed using the ip: port of access, you can modify listen ports to use
based virtual hosting: the most widely used way, above example is to use name-based virtual hosting , provided that you have multiple domain names corresponding to each site, fill in the domain name to a different server_name

nginx add account password verification

server {
    location / { auth_basic "please input user&passwd"; 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

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: file is displayed when the time off (default) to GMT time; read on after , file time display for the server time
by default when the contents of the file will be displayed on the browser when txt file access and so forth, if you want to download the browser directly, plus the following configuration

if ($request_filename ~* ^.*?\.(txt|pdf|jpg|png)$) { add_header Content-Disposition 'attachment'; }

Configuring the default site

server {
    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

Do not allow access by IP

server {
    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 to
the top of this method is relatively rough, of course, you can also configure all addresses that are not configured 301s directly to your website to visit to, you can also bring a certain website traffic

server {
    rewrite ^/(.*)$ https://blog.linuxbaodian.com/$1 permanent; }

Direct verification file returns

location = /XDFyle6tNA.txt {
    default_type text/plain; return 200 '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 reverse proxy configuration upstream

http {
    ... upstream tomcats { server 192.168.106.176 weight=1; server 192.168.106.177 weight=1; } server { location /blog/ { 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 proxy_passplus bars without bars of the trap, where detail at proxy_pass http://tomcatsthe proxy_pass http://tomcats/differences:

Although only a / distinction vary but the results determined. The following two cases:
1. The target 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 /blog/ { proxy_pass http://192.168.106.135:8181; }

http://domain/blog/ –> http://192.168.106.135:8181/blog/
http://domain/blog/action/abc –> http://192.168.106.135:8181/blog/action/abc

  1. URI with the destination address ( proxy_pass http://tomcats/, /it is uri), in this case a new target url, uri partial match will be modified to the parameters uri.
location /blog/ { proxy_pass http://192.168.106.135:8181/; }

http://domain/blog/ –> http://192.168.106.135:8181
http://domain/blog/action/abc –> http://192.168.106.135:8181/action/abc

nginx upstream open keepalive

upstream tomcat {
    server blog.linuxbaodian.com: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: Specify each nginx worker can keep the maximum number of connections is 1024, not set by default, that is, nginx as a client keepalive not in effect
proxy_http_version 1.1: Turn keepalive requires HTTP protocol version 1.1 HTTP
proxy_set_header Connection "": For compatibility with older protocol and to prevent http headers have Connection close due to keepalive failure, where the need for timely cleared Connection HTTP header

404 automatically jump to the home page

server {
    location / { error_page 404 = @404page; } location @404page { 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

Nginx configuration to support high-concurrency

1, Nginx conventional optimization
edit nginx.conf, modify parameters were optimized.

worker_processes 8;

Nginx number of processes, it is recommended to specify the number of follow CPU, it is generally a multiple (e.g., two four-core CPU in terms of 8).

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000; worker_rlimit_nofile 65535;

This means that when a command is Nginx process opens up the number of file descriptors, the theoretical value should be opened up packet
number (ulimit -n) divided by the number of member nginx processes, but not so uniform Nginx allocation request, and so the best ulimit -n consistent value. Now open the file opened in linux 2.6 kernel number is 65535, worker_rlimit_nofileyou should fill out the appropriate 65535.

worker_connections 65535;

The maximum number of connections allowed per process maximum number of connections, in theory, each server is nginxworker_processes*worker_connections

keepalive_timeout 60;

keepalive timeout.

client_header_buffer_size 4k;

The client request buffer size of the head, this can be set according to the size of your paging systems, usually a request does not exceed the size of the head of 1k, but due to the general paging system should be greater than 1k, so here set page size.

open_file_cache max=65535 inactive=60s;

This will open the specified file cache is not enabled by default, max specify the number of buffers, recommendations and open the same number of files, inactive refers to delete cache files after much time has not been requested.

open_file_cache_valid 80s;

This refers to how long a cache of checking for valid information.

open_file_cache_min_uses 1;

open_file_cache directive inactive
least provided with the time parameter file number, if this number is exceeded, the file descriptor has been opened in the cache, the above example, if a file has not been used within a time inactive, it will be shifted except.

2, optimize the kernel parameter
editor sysctl.confoptimized linux kernel.

net.ipv4.tcp_max_tw_buckets = 6000

Timewait number, the default is 180,000.

net.ipv4.ip_local_port_range = 1024 65000

Allowed ports to open systems.

net.ipv4.tcp_tw_recycle = 1

Timewait enable fast recovery.

net.ipv4.tcp_tw_reuse = 1

Open reuse. TIME-WAIT sockets allow re-used for new TCP connection.

net.ipv4.tcp_syncookies = 1

Open SYN Cookies, when the SYN queue overflow occurs, enable cookies to deal with.

net.core.somaxconn = 262144

web applications listen function backlog default kernel will give us the parameters net.core.somaxconn limit to 128, but nginx default is defined NGX_LISTEN_BACKLOG 511, it is necessary to adjust this value.

net.core.netdev_max_backlog = 262144

When the rate of each fast network interface to receive packets of these packet rate than the processing cores, the maximum allowed number of packets to the queue.

net.ipv4.tcp_max_orphans = 262144

The system up to the number of TCP sockets are not linked to any user file handle. If this number is exceeded the connection will immediately be reset orphan and prints out a warning message. This restriction only to prevent simple DoS attacks, can not rely on it too much or artificially reduce this value should increase this value (if the increase in the memory after).

net.ipv4.tcp_max_syn_backlog = 262144

Those maximum client has not received confirmation of the connection request information recorded. For there is 128M of memory systems, the default value is 1024, the small memory system is 128.

net.ipv4.tcp_timestamps = 0

Time stamp sequence number to avoid winding. A 1Gbps link is sure to encounter previously used serial number. Timestamp allows the kernel to accept this "abnormal" packets. Here it needs to be turned off.

net.ipv4.tcp_synack_retries = 1

In order to open a connection end, the kernel needs to send a SYN and a SYN response is provided with a front of the ACK. That is, the so-called three-way handshake in the second handshake. This setting determines the number of cores SYN + ACK packet transmission is aborted before connection.

net.ipv4.tcp_syn_retries = 1

In establishing the number of cores give up before sending a SYN packet connection.

net.ipv4.tcp_fin_timeout = 1

If the socket is closed by the end of the claim, this parameter determines the time it remains in state FIN-WAIT-2's. Peer wrong and can never close the connection, even when the machine unexpectedly. The default value is 60 seconds. 2.2 kernel is usually the value is 180 seconds, 3 you can press this setting, but remember that even if your machine is a light load of WEB server, are also at risk because a large number of dead sockets and memory overflow, FIN - the risk of WAIT-2's FIN-WAIT-1 is smaller than that, because it can only eat up to 1.5K of memory, but their longer survival.

net.ipv4.tcp_keepalive_time = 30

When the only use of keepalive, TCP transmission frequency of keepalive messages. The default is 2 hours.
After the above optimization, Nginx can support the amount of concurrency of more than 50,000.

Nginx Security Configuration

There are too many on the network security configuration method Nginx, the paper according to their actual environment, to choose their own security Nginx configuration policies.

1, remove all unnecessary Nginx module

Nginx directly by compiling the source code module minimizes the number. By limiting access to only allow the Web server module to minimize risk. For example, disabling SSL and autoindex module you can execute the following command:

./configure without-http_autoindex_module without-http_ssi_module make make install

Which module can open an account or to close when viewed through the following command when compiling Nginx server:

./configure help | less

You then disable less than the Nginx module.

2, install SELinux policy to strengthen Nginx Web server
default SELinux will not protect Nginx Web server, install the software and build my protection here.
SELinux support needed to install the compiler environment

yum -y install selinux-policy-targeted selinux-policy-devel

Download SELinux policy to strengthen Nginx Web server.

cd /opt
wget http://downloads.sourceforge.net/project/selinuxnginx/se-ngix_1_0_10.tar.gz?use_mirror=nchc’

Unpack, compile files

tar -zxvf se-ngix_1_0_10.tar.gz

Compile file

cd se-ngix_1_0_10/nginx make

Output will be as follows:

Compiling targeted nginx module
/usr/bin/checkmodule: loading policy configuration from tmp/nginx.tmp /usr/bin/checkmodule: policy configuration loaded /usr/bin/checkmodule: writing binary representation (version 6) to tmp/nginx.mod Creating targeted nginx.pp policy package rm tmp/nginx.mod.fc tmp/nginx.mod

Nginx.pp SELinux generated by the installation module:

/usr/sbin/semodule -i nginx.pp

3, the control buffer overflow attacks

Edit nginx.conf, for all clients to set the buffer size limit.

vim /usr/local/nginx/conf/nginx.conf

Edit and set all client buffer size is limited as follows:

## Start: Size Limits & Buffer Overflows ##
client_body_buffer_size 1K; client_header_buffer_size 1k; client_max_body_size 1k; large_client_header_buffers 2 1k; ## END: Size Limits & Buffer Overflows ##

4, the control concurrent connections

NginxHttpLimitZone module limits the use of a specific session or a special case of concurrent connections IP address. Edit nginx.conf:

limit_zone slimits $binary_remote_addr 5m;
limit_conn slimits 5;

Limits indicated above for each remote client IP address to open a connection while no more than five.

5, to limit the usable request method

GET and POST are the Internet's most commonly used method. Web server method is defined in RFC 2616. If the Web server does not require all available methods enabled, they should be disabled. The following instructions will only allow filtered GET, HEAD, and POST methods:

## Only allow these request methods ##
if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; } ## Do not accept DELETE, SEARCH and other methods ##

6, a number of refuse User-Agents

You can easily stop User-Agents, such as scanners, robotics and abuse of your server spammers.

## Block download agents ##
if ($http_user_agent ~* LWP::Simple|BBBike|wget) { return 403; } ##

Soso and prevent proper way of robots:

## Block some robots ##
if ($http_user_agent ~* Sosospider|YodaoBot) { return 403; }

7, to prevent the picture Daolian

Pictures or HTML Daolian mean someone directly address your Web site with pictures to be displayed on his website. The end result, you need to pay the extra cost of broadband. We need to block and prevent hotlinking behavior.

# Stop deep linking or hot linking
location /images/ { valid_referers none blocked www.example.com example.com; if ($invalid_referer) { return 403; } }

8, the firewall level limits the number of connections for each IP

Network server must monitor connections and connections per second limit. PF and Iptales can prevent end users from accessing before entering your Nginx server.
Linux Iptables: limiting the number of connections per Nginx
following examples will prevent over 15 connect connection port 80 within 60 seconds from one of the IP.

/sbin/iptables -A INPUT -p tcp dport 80 -i eth0 -m state state NEW -m recent set sbin/iptables -A INPUT -p tcp dport 80 -i eth0 -m state state NEW -m recent update seconds 60 hitcount 15 -j DROP service iptables save

I set within the same IP 60 Miao Nginx allows only 10 links.

9: configure the operating system to protect Web servers

Nginx program running as user nginx. However, the root directory (/ nginx or / usr / local / nginx / html) should not be set to belong to the user or user nginx nginx writable. Find the error file permissions can use the following command:

find /nginx -user nginx find /usr/local/nginx/html -user nginx

Make sure you more ownership for the root or other user, a typical set of permissions

/usr/local/nginx/html/ ls -l /usr/local/nginx/html/

Sample output:

-rw-rr 1 root root 925 Jan 3 00:50 error4xx.html -rw-rr 1 root root 52 Jan 3 10:00 error5xx.html -rw-rr 1 root root 134 Jan 3 00:52 index.html

Delete the backup files created by vim or another text editor:

find /nginx -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’ find /usr/local/nginx/html/ -name ‘.?*’ -not -name .ht* -or -name ‘*~’ -or -name ‘*.bak*’ -or -name ‘*.old*’

To delete these files -delete option to the find command, caution, danger, find deleted.

10, Nginx limiting outgoing connections

Hackers use tools such as wget download your local file server. Iptables from using nginx user to block outgoing connections. ipt_owner creator module attempts to match packets generated locally. The following examples only allows user 80 connected to outside users.

/sbin/iptables -A OUTPUT -o eth0 -m owner uid-owner vivek \ -p tcp dport 80 -m state state NEW,ESTABLISHED -j ACCEPT

V. Summary
This article only according to their needs to build their own Web server, I want to help. Nginx is a good tool to improve parts, far more than the limited functionality Nginx Web server build, it had more features we still have to continue to develop, I look forward to Nginx can bring us more surprises, you can also share your comments section a good way.

Guess you like

Origin www.cnblogs.com/henrylinux/p/11516978.html
Recommended