search
HomeBackend DevelopmentPHP TutorialTutorial on deploying ThinkPHP project on Nginx, nginxthinkphp_PHP tutorial

Tutorial on deploying ThinkPHP project on Nginx, nginxthinkphp

Some time ago, I developed a small website using Apache and TP. It was also my first practical experience using TP. I am used to using the pathinfo mode, and everything runs fine locally. However, when I deploy it to the server, because the other party uses Nginx, the pathinfo mode of ThinkPHP is not supported by default, so the path error occurs and the page jumps in a loop. So, Download nginx and test it locally.

In fact, there are two solutions to solve the problem of nginx not supporting pathinfo. One is not to use pathinfo mode, and the other is to modify the configuration file of nginx so that it supports pathinfo. In order to simplify the problem, I chose the first method, because as for the second method, I checked a lot of information and found that everyone's methods are different, and some are very different, which can easily lead to misleading, so I chose to simplify Set off and choose normal mode, although there are certain risks. After modifying the front-end code corresponding to index.php, we found that the front-end was basically normal, but the redirection problem still occurred in the back-end. After struggling for a long time, I thought of taking a look at the log file. It turned out to be a problem with the editor. It seemed that the log file was really important, and I had never paid attention to it before. The output appears on the first line of the config.php file,

Under sublime, a BOM header is usually added to the UTF-8 file. This BOM header is usually invisible under window and can be viewed through other editors. It can also be seen directly under Linux and is usually displayed. It is a garbled character, just delete this character, or simply press Enter on the first line and delete it. At this point, the backend is basically accessible.

There are a few small issues that need to be explained.

1. When logging in, I sent an Ajax request through an external js file for verification. I encountered some problems in the communication between js and the ThinkPHP module function. I never knew how to write the correct path, and I did not find any relevant information. I can only try various data. Fortunately, I found a solution. By directly bringing the entry file name, the code is as follows

Copy code The code is as follows:

var url="system.php?m=Login&a=doLog";
$.post(url,{"staffname":$staffname,"staffpwd":$staffpwd,"verifycode":$verifycode},function(data){
If(data=="codeerr"){
alert("Verification code is wrong!");
}else if(data=="authempty"){
alert("Please enter username or password!")
}else if(data=="autherr"){
alert("Username or password is wrong!");
}else if(data=="success"){
alert("Login successful!");
location.href="system.php?m=Index&a=index"; //Visit the homepage
}

Of course, this is the access method in normal mode. If it is pathinfo, you only need to modify the red part as follows

Copy code The code is as follows:

var url="doLog";
$.post(url,{"staffname":$staffname,"staffpwd":$staffpwd,"verifycode":$verifycode},function(data){
If(data=="codeerr"){
alert("Verification code is wrong!");
         }else if(data=="authempty"){
alert("Please enter username or password!")
         }else if(data=="autherr"){
alert("Wrong username or password!");
         }else if(data=="success"){
alert("Login successful!");
location.href="../Index/index"; //How to jump to the homepage and access other modules

2. When downloading files, there are always a lot of html things inexplicably. The reason is that the buffer is not cleared. It can be modified by the following code, but in this way, the files actually downloaded are still in html format. I just changed the suffix to xls, so when you open it with excel, you will be prompted with a format problem, just ignore it. At the same time, you need to pay attention to using the icov() function to convert the encoding, because the default encoding format of xls is not utf-8.

Copy code The code is as follows:

ob_start();
ob_end_clean();
Header( "Content-type: application/octet-stream"); ​​
Header( "Accept-Ranges: bytes ");
Header( "Content-type:application/vnd.ms-excel;charset=gb2312");
Header( "Content-Disposition:attachment;filename={$filename}.xls");

3. You will encounter path problems when deleting files, because most of the projects use relative paths, that is, relative to the entry files, but deleting files requires using absolute paths. I have not found a suitable solution. Method, I had to use a more conservative approach, the code is as follows

Copy code The code is as follows:

$path="./Public/uploads/";
$path=str_replace("\","/",realpath($path)."/"); //Get the absolute path and convert the separator

4. In terms of configuring nginx and php, I used fastCGI, saved the following code as a cmd file, and just click to run it

"F:phpphp-cgi.exe" -b 127.0.0.1:9000 -c "F:phpphp.ini" //Following is the path of the php file
​ ​ Then add a few sentences to the nginx configuration file

Copy code The code is as follows:

location ~ .php/?.* {
root                   fastcgi_pass 127.0.0.1:9000;
                    fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                                                                                                                        include     ​​​​​​ #Define variable $path_info, used to store pathinfo information
                 set $path_info "";
​​​​​​​ #Define variable $real_script_name, used to store the real address
                set $real_script_name $fastcgi_script_name;
                #If the address matches the regular expression within quotes
If ($fastcgi_script_name ~ "^(.+?.php)(/.+)$") {
                                          #Assign the file address to the variable $real_script_name
set $real_script_name $1;
                                                   #Assign the parameters after the file address to the variable $path_info
                                set $path_info $2;
            }
​​​​​​​ #Configure some parameters of fastcgi
                fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
                 fastcgi_param SCRIPT_NAME $real_script_name;
                  fastcgi_param PATH_INFO $path_info;
         }

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/951641.htmlTechArticleTutorial on deploying ThinkPHP project on Nginx, nginxthinkphp I developed a small website using Apache and TP some time ago, which is also mine The first actual battle using TP. I'm used to using pathinfo mode...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor