Home Backend Development PHP Tutorial The simplest way to achieve cross-domain: use nginx reverse proxy

The simplest way to achieve cross-domain: use nginx reverse proxy

Jul 29, 2016 am 09:15 AM
nbsp nginx quot url

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to configure nginx in Windows How to configure nginx in Windows Apr 14, 2025 pm 12:57 PM

How to configure Nginx in Windows? Install Nginx and create a virtual host configuration. Modify the main configuration file and include the virtual host configuration. Start or reload Nginx. Test the configuration and view the website. Selectively enable SSL and configure SSL certificates. Selectively set the firewall to allow port 80 and 443 traffic.

How to start containers by docker How to start containers by docker Apr 15, 2025 pm 12:27 PM

Docker container startup steps: Pull the container image: Run "docker pull [mirror name]". Create a container: Use "docker create [options] [mirror name] [commands and parameters]". Start the container: Execute "docker start [Container name or ID]". Check container status: Verify that the container is running with "docker ps".

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to check whether nginx is started How to check whether nginx is started Apr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to create containers for docker How to create containers for docker Apr 15, 2025 pm 12:18 PM

Create a container in Docker: 1. Pull the image: docker pull [mirror name] 2. Create a container: docker run [Options] [mirror name] [Command] 3. Start the container: docker start [Container name]

How to check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

What to do if nginx server is hung What to do if nginx server is hung Apr 14, 2025 am 11:42 AM

When the Nginx server goes down, you can perform the following troubleshooting steps: Check that the nginx process is running. View the error log for error messages. Check the syntax of nginx configuration. Make sure nginx has the permissions you need to access the file. Check file descriptor to open limits. Confirm that nginx is listening on the correct port. Add firewall rules to allow nginx traffic. Check reverse proxy settings, including backend server availability. For further assistance, please contact technical support.

See all articles