search
HomeBackend DevelopmentPHP TutorialThe simplest way to achieve cross-domain: use nginx reverse proxy

What is cross-domain? Cross-domain means that the browser cannot execute scripts from other websites. It is caused by the browser's same-origin policy, which is a security restriction imposed by the browser on JavaScript. The so-called same origin means that the domain name, protocol and port are the same. When the browser executes a javascript script, it will check which page the script belongs to. If it is not the same origin page, it will not be executed. The purpose of the same-origin policy is to prevent hackers from doing criminal activities. For example, if a bank application allows users to upload web pages, if there is no same-origin policy, a hacker can write a login form and submit it to his own server, and get a page that looks quite high-end. The hacker sends this page to the user via email, etc. The user mistakenly thinks that this is the main webpage of a certain bank and logs in, which will leak their user data. And because of the browser's same-origin policy, hackers cannot receive form data. Now with the popularity of RESTFUL, many applications provide APIs with http/https interfaces and provide services to the outside world through xml/json format to achieve an open architecture. For example, websites and applications such as Weibo, WeChat, Weather Forecast, and openstack all provide restful interfaces. Web applications are also developing towards single pages. More and more web applications now have this architecture: Static single web pageajaxCallRESTFUL serviceWe could have used the APIs provided by various websites to make many wonderful web applications . However, the cross-domain restrictions when browsers execute JavaScript have become a stumbling block for this type of open architecture. This article proposes a simple and effective way to solve cross-domain problems. Commonly used cross-domain methodsCommonly used cross-domain methods include the following: 1. Use iFrame to access another domain. Then read the contents of the iFrame from another page. There are some packages for jquery and so on. It is said that Firefox and others may not support reading the content of another iFrame. 2,jsonp. Requires server support. Use script src to dynamically get a piece of java code. It is the js function on the callback page, and the parameter is a json object. jquery also has encapsulation. 3. Set the http header, Access-Control-Allow-Origin: *But it is said that some versions of IE do not recognize this http header. 4, server proxy. For example, the server writes a url processing action. Its parameter is a url. This server will use parameters to piece together a URL, use the httpclient library to execute the URL, and then output the read content to the http client. nginx reverse proxy realizes cross-domainThe cross-domain methods mentioned above all have some problems. Some cannot support all browsers, some need to modify the javascript code, and some need to rewrite the server-side code. Some may have problems in scenarios such as sessions. In fact, using nginx reverse proxy to achieve cross-domain is the simplest cross-domain method. You only need to modify the configuration of nginx to solve cross-domain problems. It supports all browsers and sessions, does not need to modify any code, and will not affect server performance. We only need to configure nginx and configure multiple prefixes on one server to forward http/https requests to multiple real servers. In this way, all URLs on this server have the same domain name, protocol and port. Therefore, for browsers, these URLs are of the same origin and there are no cross-domain restrictions. And in reality, these URLs are actually served by physical servers. The javascript within these servers can call URLs on all these servers across domains. Below, an example of nginx supporting cross-domain is given for detailed explanation. For example, we have two projects developed by pythonflask: testFlask1 and testFlask2. The javascript script on the testFlask2 project needs to call a url of testFlask1 through ajax to obtain some data. Under normal deployment, there will be cross-domain problems, and the browser will refuse to execute calls like the following.

1

2

3

4

5

$("button").click(function () {

    $.get("127.0.0.1:8081/partners/json", function(result) {

        $("div").html(result);

    });

});

Let’s modify the javascrip file of the testFlask2 project. In this way, there will be no cross-domain problems when accessing URLs from the same source.

1

2

3

4

5

$("button").click(function () {

    $.get("partners/json", function(result) {

        $("div").html(result);

    });

});

However, our testFlask2 project actually does not have a url like partners/json, so how to deal with it? We write the nginx configuration file like this:

1

2

3

4

5

6

7

8

9

10

11

12

server{

listen8000;

location/ {

includeuwsgi_params;

uwsgi_passunix:/tmp/testFlask2.sock;

  }

  location/partners {

    rewrite^.+partners/?(.*)$ /$1 break;

    includeuwsgi_params;

    uwsgi_passunix:/tmp/testFlask1.sock;

  }

}

We deployed the testFlask2 project in the root directory of port 8080. Deploy the testFlask1 project that provides web services in the /partners directory. But our testFlask1 project cannot handle url requests like /partners/json. then what should we do? By rewrite^.+partners/?(.*)$ /$1 break; this command, nginx can convert all received /partners/* requests into /* requests and then forward them to the real web server behind it. In this way, RESTFUL's ajax client program only needs to give the URL with a specific prefix to call the RESTFUL interface provided by any server. Even, through the reverse proxy of nginx, we can call the RESTFUL interface provided by websites developed by other companies. Such as,

1

2

3

4

5

location/sohu {

rewrite^.+sohu/?(.*)$ /$1 break;

includeuwsgi_params;

proxy_passhttp://www.sohu.com/;

}

We will move the entire sohu website to our 8080:/sohu/ directory, and our javascript can freely call its RESTFUL service. By the way, rewrite^.+sohu/?(.*)$ /$1 break; In this command, $1 represents the (.*) part. The parameters in the first pair () are $1, the parameters in the second pair () are $2, and so on. SummaryThis article introduces how to use the reverse proxy function of nginx to achieve cross-domain access to any application and website. nginx is a high-performance web server commonly used as a reverse proxy server. As a reverse proxy server, nginx forwards http requests to another or some servers. Cross-domain access can be achieved by mapping a local url prefix to the web server to be accessed cross-domain. For the browser, what you access is a URL on the same origin server. And nginx forwards the http request to the real physical server behind by detecting the url prefix. And remove the prefix through the rewrite command. This way the real server can handle the request correctly and not know that the request came from the proxy server. Simply put, the nginx server deceives the browser into thinking that it is a same-origin call, thereby solving the browser's cross-domain problem. By rewriting the URL, it deceives the real server into thinking that the http request comes directly from the user's browser. In this way, in order to solve the cross-domain problem, you only need to change the nginx configuration file. Simple, powerful and efficient!

The above introduces the simplest method to achieve cross-domain: using nginx reverse proxy, including aspects of the content, I hope it will be helpful to friends who are interested in PHP tutorials.

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 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.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools