In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to install and configure nginx". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to install and configure nginx".
Server basic configuration remote linked server ssh user name @ public network ip
The default user name is root. If the public network ip is a.b.c.d, the link name is
Ssh root@a.b.c.d downloads and installs the base library yum-y install gcc gcc-c++ autoconf pcre pcre-devel make automakeyum-y install wget httpd-tools vim to close iptables
View iptables rules
Iptables-L or iptables-t nat-L
Turn off the iptables rule
Iptables-F or iptables-t nat-F turns off SELinux
Check to see if it is open
Getenforce
Close
Introduction and installation of setenforce 0II and Nginx
Nginx is an open source, high-performance, high-reliable HTTP middleware, proxy service.
Install Nginx
Open the official website nginx.org/en/linux_pa …
To set up the yum repository for RHEL/CentOS, create the file named / etc/yum.repos.d/nginx.repo with the following contents:
[nginx] name=nginx repobaseurl= http://nginx.org/packages/OS/OSRELEASE/$basearch/gpgcheck=0enabled=1
Replace "OS" with rhel "or" centos ", depending on the distribution used, and" OSRELEASE "with" 6 "or" 7 ", for 6.x or 7.x versions, respectively.
Installation directory and configuration explanation 3.1 installation directory explanation
View all installation directories for nginx
Rpm-ql nginx
And then get the following configuration
[root@ ~] # rpm-ql nginxnginx log rotation, related to log slicing / etc/logrotate.d/nginxnginx main configuration file / etc/nginx/nginx.conf/etc/nginx/etc/nginx/conf.d/etc/nginx/conf.d/default.confcgi configuration for logrotate service Fastcgi configuration / etc/nginx/fastcgi_params/etc/nginx/scgi_params/etc/nginx/uwsgi_params Transcoding Transformation Mapping conversion File / etc/nginx/koi-utf/etc/nginx/koi-win/etc/nginx/win-utf Settings Content-Type and extension correspondence of http Protocol / etc/nginx/mime.types is used to configure the daemon manager management mode of the system / etc/sysconfig/nginx/etc/sysconfig/nginx-debug/usr / lib/systemd/system/nginx-debug.service/usr/lib/systemd/system/nginx.servicenginx module directory / startup management terminal commands for etc/nginx/modules/usr/lib64/nginx/modules/usr/lib64/nginx/usr/libexec/initscripts/legacy-actions/nginx/usr/libexec/initscripts/legacy-actions/nginx/check-reload/usr/libexec/initscripts/legacy-actions/nginx/upgradenginx services / usr/sbin/nginx/usr/sbin/nginx-debugnginx manual and Help file / usr/share/doc/nginx-1.14.0/usr/share/doc/nginx-1.14.0/COPYRIGHT/usr/share/man/man8/nginx.8.gz/usr/share/nginx/usr/share/nginx/html/usr/share/nginx/html/50x.html/usr/share/nginx/html/index.htmlnginx cache directory / var/cache/nginxnginx log directory / var/log/nginx3.2 installation compilation parameters
Command nginx-V to view all compilation parameters
3.3 Nginx default configuration syntax parameters indicate that user sets the number of user worker_processes worker processes used by the system of the nginx service (generally consistent with the number of server cores) rror_lognginx error log pidnginx service startup pidevents-> worker_connections maximum number of connections per process events-> default profile for number of use worker processes nginx
File path / etc/nginx/conf.d/default.conf
Server {listen 80; server_name localhost; # charset koi8-r; # access_log / var/log/nginx/host.access.log main; location / {root / usr/share/nginx/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 / usr/share/nginx/html;} # proxy the PHP scripts to Apache listening on 127.0.0.1 virtual 80 # # location ~. Php$ {# proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1 pass the PHP scripts to FastCGI server listening on 9000 # # location ~\. Php$ {# root html; # fastcgi_pass 127.0.0.1 php$ 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; #}}
You can go to / usr/share/nginx/html/index.html to modify the default display page, or you can go to / usr/share/nginx/html/50x.html to modify the error page.
Restart nginx after modification
Systemctl reload nginx.service or systemctl restart nginx.service
Check the nginx configuration, and successful indicates success
Nginx-t-c / etc/nginx/nginx.conf
Reload configuration
Nginx-s reload-c / etc/nginx/nginx.conf IV. Common Nginx Intermediate Architecture
Static resource WEB service
Agent service
Load balancer scheduler SLB
Dynamic caching
4.1 static Resource WEB Service
Configuration Syntax-File read Syntax: sendfile on | off;Default: sendfile off;Context: http,server,location,if in location
Introduction:-- with-file-aio asynchronous file reading
Configuration syntax-tcp_nopushSyntax: tcp_nopush on | off;Default: tcp_nopush off;Context: http,server,location configuration syntax-tcp_nodelaySyntax: tcp_nodelay on | off;Default: tcp_nodelay on;Context: http,server,location configuration syntax-compression Syntax: gzip_comp_level level;Default: gzip_comp_level 1 itself context: http,server,locationSyntax: gzip_http_version 1.0 | 1.1 position default: gzip_http_version 1.1 Context: http,server,location extension Nginx compression module pre-read gzip function http_gzip_static_module application supports gunzip compression http_gunzip_module browser cache settings
Configuration Syntax-expires
Add Cache-Control, Expires header
Syntax:expires [modified] time; expires epoch | max | offDefault: expires off;Context: http, server, location, if in location Cross-domain
* indicates that all websites are allowed to cross-domain, and only required URLs can be set for security reasons.
Location ~. *\. (htm | html) ${add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS; root / opt/app/code} based on http_refer hotlink protection configuration module Syntax: valid_referers none | blocked | server_names | string...;Default:-Context: server, location,4.2 proxy service
The difference between a forward proxy and a reverse proxy is that the object of the proxy is different.
The object of the forward proxy is the client
The object of the reverse proxy is the server
Configuration syntax
Syntax: proxy_pass URLDefault:-Context: location,if in location,limit_except
There are generally three types of URL
Http://localhost:8080/uri/https://192.168.1.1:8000/uri/http://unix:/tmp/backend.socket:/uri/;4.3 load balancing HttpIndex module
This module provides a simple way to balance the load of the back-end server between polling and client IP.
Sample configuration:
Resolver 10.0.0.1 upstream dynamic {zone upstream_dynamic 64k; hash $request_uri; # is allocated according to the hash value of url, and the same url is assigned to the same server server backend1.example.com weight=5; server backend2.example.com:8080 fail_timeout=5s slow_start=30s; server 192.0.2.1 max_fails=3; server backend3.example.com resolve; server backend4.example.com service=http resolve Server backup1.example.com:8080 backup; server backup2.example.com:8080 backup;} server {location / {proxy_pass http://dynamic; health_check;}}
State interpretation
Configuration indicates that the current server of down does not participate in the backup server reserved by load balancer backup the number of requests allowed to fail fail_timeout after the failure of max_fails, the time of service suspension max_conns limits the maximum number of connections received scheduling algorithm configuration indicates that polling is distributed one by one to non-stop back-end servers in chronological order, the greater the weighted polling weight value The higher the probability of access assigned, the higher the probability of ip_hash each request is allocated according to the hash result of accessing the IP, so that the request is regularly accessed from the same ip a back-end server url_hash distributes the request according to the hash result of the accessed URL, so that each URL is directed to the same back-end server least_conn with the minimum number of connections, and which machine has fewer connections will distribute the hash key value hash custom key4.4 cache.
Cache type classification: client cache, proxy cache, server cache
Proxy_cache
Syntax: proxy_cache zone | off;Default: proxy_cache off;Context: http, server, location
Proxy_cache_path
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on | off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on | off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; Default:-Context: http
Example
Proxy_cache_path / data/nginx/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m use_temp_path=off;map $request_method $purge_method {PURGE 1; default 0;} server {... Location / {proxy_pass http://backend; proxy_cache cache_zone; proxy_cache_key $uri; proxy_cache_purge $purge_method # assign another server when there is a 50x error in the assigned server proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504} V, Nginx Deep Learning 5.1 Separation of upstream java_api {server 127.0.0.1 upstream java_api 8080 } server {... # matches the request at the end of jsp to request the server location ~\ .jsp$ {proxy_pass http://java_api; index index.html index.htm;} # to match the local content returned by the image resource location ~\. (jpg | png | gif) ${expires 1h; gzip on;}} 5.2Nginx rewrite rule
Purpose: to achieve url rewriting and redirection
Use the scene:
URL access redirection to support development and design
Page jump, compatibility support, display effect, etc.
SEO optimization
Maintain. Background maintenance, traffic forwarding, etc.
Safety
Grammar
Syntax: rewrite regex replacement [flag]; Default:-Context: server, location, if
If the specified regular expression matches the request URI, the URI changes as specified in the * replacement* string. Rewrite instructions are executed in the order in which they appear in the configuration file. You can use flags to terminate further processing of instructions. If the replacement string begins with "http://","https://"," or "$scheme," processing stops and the redirection is returned to the client.
The optional * flag* parameter can be:
Last
Stop rewrite detection
Stop processing the current "ngx_http_rewrite_module" instruction set and start searching for new locations that match the changed URI
Break
Stop rewrite detection
Stop processing the current "ngx_http_rewrite_module" instruction set, just as you would with break instructions
Redirect
Return to 302 temporary redirection, and the address bar will display the jumped address.
Returns a temporary redirect with a 302 code; used when the replacement string does not start with "http://"," https://", or "$scheme"
Permanent
Return to 302 permanent redirection, and the address bar will display the jumped address.
Returns a permanent redirect with a 301 code.
The complete redirect URL is formed based on the request scheme ($scheme) and "theserver_name_in_redirect" and "port_in_redirect" instructions.
Example:
Server {... Rewrite ^ (/ download/.*) / media/ (. *)\.. * $1/mp3/$2.mp3 last; rewrite ^ (/ download/.*) / audio/ (. *)\.. * $$1/mp3/$2.ra last; return 403;.}
However, if these instructions are placed in the position "/ download/", the last flag should be replaced with break, otherwise nginx will loop 10 times and return 500 errors.
Location / download/ {rewrite ^ (/ download/.*) / media/ (. *)\.. * $1/mp3/$2.mp3 break; rewrite ^ (/ download/.*) / audio/ (. *)\. * $1/mp3/$2.ra break; return 403;}
If a * replacement* string contains new request parameters, the previous request parameters are appended to them. If you don't want this to happen, for example, by adding a question mark at the end of the replacement string, you can avoid appending these parameters.
Rewrite ^ / users/ (. *) $/ show?user=$1? Last
If a regular expression includes "}" or ";" characters, the entire expression should be enclosed in single or double quotation marks.
5.3 Security check secure_link
Specify and allow to check the authenticity of the requested link and protect resources from unauthorized access
Limit the effective period of a link
Syntax: secure_link expression;Default:-Context: http, server, locationSyntax: secure_link_md5 expression;Default:-Context: http, server, location
Example:
Location / s / {secure_link $arg_md5,$arg_expires; secure_link_md5 "$secure_link_expires$uri$remote_addr secret"; if ($secure_link = "") {return 403;} if ($secure_link = "0") {return 410;}.} 5.3 geoip_module module
Match MaxMind GeoIP binary files based on IP address and read the region information of IP
Installation: yum install nginx-module-geoip
Working with scen
Make HTTP access rules at home and abroad
Make HTTP access rules by distinguishing domestic urban areas
5.4.Configuring HTTPSserver {listen 443 ssl; server_name www.example.com; ssl_certificate www.example.com.crt; ssl_certificate_key www.example.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers Higg Vista NULL Vol Md 5;} HTTPS service optimization
Activate keepalive persistent connection
Set up ssl session cach
Server {listen 443; server_name 116.62.103.228 jeson.t.imooc.io; keepalive_timeout 100; ssl on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_certificate www.example.com.crt; ssl_certificate_key www.example.com.key; index index.html index.htm; location / {root / opt/app/code 5.5 Nginx and Lua development
Lua is a concise, lightweight and extensible scripting language
Nginx + Lua advantages: fully combine the advantages of Nginx's concurrent processing epoll and the lightweight of Lua to achieve simple functions and high concurrency scenarios.
There are two ways to install yum install lua and run lua: command line and script
Command line mode
Enter lua on the command line to turn on the command line interaction mode
Script mode
Write test.lua file, execute lua test.lua run
Comments-- Line comments-- [[Block comments -]] VI. Nginx FAQ priority of multiple server_name
If multiple files are configured with the same server_name, the configuration of which file will be loaded according to the file name read first
Location matching priority = perform exact matching of ordinary characters, that is, exact matching ^ ~ means ordinary character matching, and use prefix matching ~\ ~ * to perform a regular match ()
After the first two matches, they will not continue to match, and the last one will continue to match. If there is no match, use its match. That is, the first two priorities are higher than the third.
The use of try_files
Check the existence of files sequentially
Location / {try_files $uri $uri/ / index.php;} VII. Nginx performance optimization 7.1 file handle
File handle: linux\ Unix everything is a file, and the file handle is an index
Setting mode: system global modification, user local modification, process local modification
Modify method:
System global modification and user modification of vim / etc/security/limits.conf
Add the following code
# set root soft nofile 10000root hard nofile 1000 settings for root users and global settings for all users * soft nofile 10000 * hard nofile 10000
Soft is not mandatory. Exceeding the set value will remind you but not enforce it; hard will enforce it.
Modify vim / etc/nginx/nginx.conf for the process
Add the following code
Worker_rlimit_nofile 200007.2 CPU affinity
View the number of CPU on the current server
Cat / proc/cpuinfo | grep "physical id" | sort | uniq | wc-l
Check the number of CPU cores
Cat / proc/cpuinfo | grep "cpu cores" | uniq
Worker_processes = number of CPU * number of CPU cores
If there are 2 CPU and each CPU has 8 cores, then the worker_processes should be 16
Open the nginx configuration file vim / etc/nginx/nginx.conf
Worker_processes 16 is workerworthy, cputated auto
Then refresh the nginx configuration nginx-s reload-c / etc/nginx/nginx.conf
7. General configuration of Nginx: user nginx;worker_processes 1: workerships cputative auto;error_log / var/log/nginx/error.log warn;pid / var/run/nginx.pid;worker_rlimit_nofile 10000 × events {use epoll; worker_connections 1024;} http {include / etc/nginx/mime.types; default_type application/octet-stream; charset utf-8 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; sendfile on; # tcp_nopush on; keepalive_timeout 65; gzip on Gzip_disable "MSIE [1-6]\."; gzip_http_version 1.1; include / etc/nginx/conf.d/*.conf;} VIII. Common malicious acts and preventive measures based on Nginx architecture.
Common malicious behavior: crawler behavior and malicious crawling, resource embezzlement
Common precautions:
Basic hotlink protection: aims to prevent malicious users from easily crawling website data
Secure_link_module: improve data security, add encryption verification and invalidation to data, suitable for core important data
Access_module: provide IP prevention and control for data served by backend and some users
8.2 Common means of attack background password hits the library
Constantly try to log in to the background system by guessing the password field to obtain the background login password
Precautions:
Background login password complexity
Access_module provides IP prevention and control to the background.
Early warning mechanism
File upload vulnerability location ^ / upload {root / opt/app/images; if ($requst_filename ~ * (. *)\ .php) {return 403;}} SQL injection
Use the attack method of unfiltered / unaudited user input to make the application run SQL code that should not have run
Thank you for your reading, the above is the content of "how to install and configure nginx". After the study of this article, I believe you have a deeper understanding of how to install and configure nginx, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.