With more and more project modules, many modules are now deployed independently. Communication between modules may sometimes be accomplished through cookies. For example, the portal and the application are deployed in different machines or web containers respectively. If the user logs in, a cookie will be written on the browser client (recording the user context information), and the application wants to obtain the cookie under the portal, which will cause Solve the problem of cookie cross-domain.
Solution to cookie cross-domain problem nginx reverse proxy
Reverse proxy concept
Reverse proxy The (Reverse Proxy) method refers to using a proxy server to accept connection requests on the Internet, and then forward the request to the server on the internal network; and return the results obtained from the server to the client requesting the connection on the Internet. At this time, the proxy The server appears as a server to the outside world.
The reverse proxy server is like the original server to the client, and the client does not need to make any special settings. The client sends a normal request to the content in the reverse proxy's namespace (name-space), and then the reverse proxy will determine where to forward the request (original server) and return the obtained content to the client, like these The content is its own original content.
Scenario Simulation
Two projects, web1 and web2, are deployed on different tomcats on the same machine. Request the index.html of the web1 project, as follows:
Then click the link to request the index.jsp of the web2 project. The content is as follows:
Look at the nginx configuration again:
Using nginx's direction proxy to solve the cookie cross-domain problem is actually achieved by "cheating" the browser. Through nginx, we can put cookies from different projects under the nginx domain. Through nginx The reverse proxy can obtain cookies written by different projects.
In fact, in the above scenario, the path in $.cookie("user", "hjzgg", {path: "/web"}); can be written as "/", so that the nginx configuration is more convenient. To keep it simple, it is as follows.
location /web1 { proxy_pass http://web1; proxy_set_header Host 127.0.0.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Cookie $http_cookie; log_subrequest on; } location /web2 { proxy_pass http://web2; proxy_set_header Host 127.0.0.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Cookie $http_cookie; log_subrequest on; }
For more Nginx related technical articles, please visit the Nginx Usage Tutorial column to learn!
The above is the detailed content of How Nginx solves cross-domain cookies. For more information, please follow other related articles on the PHP Chinese website!