search
HomeBackend DevelopmentPHP TutorialNginx dynamic and static separation operation explanation

Nginx has strong static processing capabilities, but insufficient dynamic processing capabilities. Therefore, dynamic and static separation technology is commonly used in enterprises. The dynamic and static separation technology actually uses a proxy method. In the server{} section, a location with a regular match is added to specify the matching item. Dynamic and static separation for PHP: static pages are handed over to Nginx for processing, and dynamic pages are handed over to the PHP-FPM module or Apache. . In the Nginx configuration, different processing methods for static and dynamic pages are implemented through the location configuration section and regular matching.


Nginx dynamic and static separation operation explanation

1. Project brief description

Deploy wordpress to realize the dynamic separation of the entire website and achieve the following requirements:

1. The front-end Nginx receives the static request and returns it directly from NFS to the client.

2. The front-end Nginx receives the dynamic request and forwards it to the PHP server for processing through FastCGI.

----If you get a static result, directly retrieve the result from NFS and give it to Nginx and then return it to the client.

----If data processing is required, the PHP server will connect to the database and return the results to Nginx

3. The front-end Nginx receives the image request and submits it as .jpg, .png, .gif, etc. Processed by the backend Images server.

Nginx dynamic and static separation operation explanation

2. Overall architecture diagram

Nginx dynamic and static separation operation explanation

3. Configuration details

1.NFS server configuration

vim /etc/exports
/app/blog   10.10.0.0/24(ro,sync,root_squash,no_all_squash) # 只允许内网网段挂载,提高安全性。

cd /app/blog                                                # 将wordpress文件解压
tar  -xvf  wordpress-4.8.1-zh_CN.tar.gz

2.Nginx server configuration

First of all, both Nginx and PHP servers must be installed Load NFS. Achieve unified deployment and facilitate management

mount 10.10.0.72:/app/blog /app/blog #Mount NFS/app/blog to local/app/blog

and then configure Nginx

Nginx is mainly the configuration of location in the server. Configure the location to hand the file ending in .php to the PHP server. Give the ones ending in .jpg or gif to Image. Other configurations can be left as default.

vim /etc/nginx/nginx.conf
http {
    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;
    tcp_nodelay             on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80 default_server;
        server_name  www.shuaiguoxia.com;
        index index.php index.html;
        root /app/blog;                                     # 根目录为挂载的NFS的挂载点
        include /etc/nginx/default.d/*.conf;
        location ~* \.php$ {                                # location匹配将php结尾的交给PHP服务器
                fastcgi_pass 10.10.0.22:9000;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME /app/blog$fastcgi_script_name;
                include fastcgi_params;
        } 
        location ~* \.(jpg|gif)$ {                          # location匹配将图片交给Image处理
                proxy_pass http://10.10.0.23:80;            # Image服务器要开启web服务
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

3.PHP server configuration

PHP服务器的配置比较简单,主要讲PHP以FPM模式安装后进行简单的配置即可

yum install php-fpm php-mysql
vim /etc/php-fpm.d/www.conf
listen = 9000                                   # 只写监听端口,即监听所有IP
listen.allowed_clients = any                    # 允许所有IP进行访问。或者将这行注释。

4.MySQL服务器

yum install marirdb-server
/usr/local/mysql/bin/myhsql_secure_installation         #MySql初始化脚本,以下为每一项的翻译
  是否设置root密码
  输入密码
  确认密码
  是否设置匿名用户
  是否允许root远程登录
  删除test数据库
  现在是否生效
 
mysql -uroot -p 

create database wpdb;                                   # 创建wp数据库
grant all on wpdb.* to wpadm@'10.10.%' idenfied by 'centos';    # 授权用户。用户不存在系统会自动创建

5.Image服务器配置

yum install nginx                               # 安装Nginx
cd /app/image                                   # 将所有图片解压至此路径。图片的目录结构要保持原样
tar  -xvf  wordpress-4.8.1-zh_CN.tar.gz
 server {
        root      /app/image;                   # 仅仅修改根目录这一行即可。Httpd同理
        }                                       # 如果使用apache要注意在CentOS7下默认拒绝所有
nginx start                                     # 启动服务

6.配置wordpress

cp wp-config-sample.php wp-config.php           # 复制一个模板文件后改名作为主配置文件

vim wp-config.php
/** WordPress数据库的名称 */  
define('DB_NAME', 'wpdb');                      # wpdb为MySQL中创建的数据库

/** MySQL数据库用户名 */
define('DB_USER', 'wpadm');                     # wpadm为MySQL中授权的用户

/** MySQL数据库密码 */
define('DB_PASSWORD', 'centos');                # 授权用户的密码

/** MySQL主机 */
define('DB_HOST', '10.10.0.24');                # MySQL主机地址

至此配置就已经完成。达到了图片从图片服务器返回,静态nginx直接返回,动态交给PHP进行处理。

总结

1.前端Nginx要做好location匹配,将*.php与*.jpg等进行反向代理。

2.后端PHP服务器要修改配置文件,PHP自带配置文件只监听本地,且只允许本地访问

3.后端Image服务器,不论是apache还是Nginx要开启WEB服务。根目录要指向图片根目录,且根目录下的图片要与原本图片文件目录结构一致。

Related recommendations:

Nginx dynamic and static separation classic case configuration

The above is the detailed content of Nginx dynamic and static separation operation explanation. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use