DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • HTTP API: Key Skills for Smooth Integration and Operation, Part 2
  • Designing Communication Architectures With Microservices
  • Build a Time-Tracking App With ClickUp API Integration Using Openkoda
  • What Is API-First?

Trending

  • Explainable AI: Seven Tools and Techniques for Model Interpretability
  • From JSON to FlatBuffers: Enhancing Performance in Data Serialization
  • Using Agile To Recover Failing Projects
  • Phased Approach to Data Warehouse Modernization
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. CORS Anywhere on Pure NGINX Config

CORS Anywhere on Pure NGINX Config

Explore how to simplify cross-domain API access using a universal NGINX configuration that utilizes the proxy_pass directive for external sources.

By 
Alexey Shepelev user avatar
Alexey Shepelev
DZone Core CORE ·
Mar. 05, 24 · Tutorial
Like (14)
Save
Tweet
Share
4.4K Views

Join the DZone community and get the full member experience.

Join For Free

Cross-Origin Resource Sharing (CORS) often becomes a stumbling block for developers attempting to interact with APIs hosted on different domains. The challenge intensifies when direct server configuration isn't an option, pushing developers towards alternative solutions like the widely-used cors-anywhere. However, less known is the capability of NGINX's proxy_pass directive to handle not only local domains and upstreams but also external sources, for example:

proxy_pass directive example


This is how the idea was born to write a universal (with some reservations) NIGNX config that supports any given domain.

Understanding the Basics and Setup

CORS is a security feature that restricts web applications from making requests to a different domain than the one that served the web application itself. This is a crucial security measure to prevent malicious websites from accessing sensitive data. However, when legitimate cross-domain requests are necessary, properly configuring CORS is essential.

The NGINX proxy server offers a powerful solution to this dilemma. By utilizing NGINX's flexible configuration system, developers can create a proxy that handles CORS preflight requests and manipulates headers to ensure compliance with CORS policies. Here's how:

Variable Declaration and Manipulation

With the map directive, NGINX allows the declaration of new variables based on existing global ones, incorporating regular expression support for dynamic processing. For instance, extracting a specific path from a URL can be achieved, allowing for precise control over request handling.

map directive example


Thus, when requesting http://example.com/api, the $my_request_path variable will contain api.

Header Management

NGINX facilitates the addition of custom headers to responses via add_header and to proxied requests through proxy_set_header. Simultaneously, proxy_hide_header can be used to conceal headers received from the proxied server, ensuring only the necessary information is passed back to the client.

add_header example


We now have an X-Request-Path header with api.

Conditional Processing

Utilizing the if directive, NGINX can perform actions based on specific conditions, such as returning a predetermined response code for OPTIONS method requests, streamlining the handling of CORS preflight checks.

if directive example


Putting It All Together

First, let’s declare $proxy_uri that we will extract from $request_uri:

Declare $proxy_uri to extract from $request_ur


In short, it works like this: when requesting http://example.com/example.com, the $proxy_uri variable will contain https://example.com. 

From the resulting $proxy_uri, extract the part that will match the Origin header:

From the resulting $proxy_uri, extract the part that will match the Origin header


For the Forwarded header, we need to process 2 variables at once:

For the Forwarded header, we need to process 2 variables at once


The processed X-Forwarded-For header is already built into NGINX.

Now we can move on to declaring our proxy server:

Declaring proxy server


We get a minimally working proxy server, which can process the CORS Preflight Request and add the appropriate headers.

Enhancing Security and Performance

Beyond basic setup, further refinements can improve security and performance: 

Hiding CORS Headers

When NGINX handles CORS internally, it's beneficial to hide these headers from client responses to prevent exposure of server internals.

Hide these headers from client responses to prevent exposure of server internals


Rate Limit Bypassing

It would also be nice to pass the client’s IP to somehow bypass the rate limit, which can occur if several users access the same resource.

Pass the client’s IP to bypass the rate limit


Disabling Caching

And finally, for dynamic content or sensitive information, disabling caching is a best practice, ensuring data freshness and privacy.

Disabling caching


Conclusion

This guide not only demystifies the process of configuring NGINX to handle CORS requests but also equips developers with the knowledge to create a robust, flexible proxy server capable of supporting diverse application needs. Through careful configuration and understanding of both CORS policies and NGINX's capabilities, developers can overcome cross-origin restrictions, enhance application performance, and ensure data security. This advanced understanding and application of NGINX not only solves a common web development hurdle but also showcases the depth of skill and innovation possible when navigating web security and resource-sharing challenges.

Cache (computing) Directive (programming) Proxy pattern Integration API integration

Opinions expressed by DZone contributors are their own.

Related

  • HTTP API: Key Skills for Smooth Integration and Operation, Part 2
  • Designing Communication Architectures With Microservices
  • Build a Time-Tracking App With ClickUp API Integration Using Openkoda
  • What Is API-First?

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: