> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/fastapi/fastapi/llms.txt
> Use this file to discover all available pages before exploring further.

# HTTPSRedirectMiddleware

> Automatically redirect HTTP requests to HTTPS in your FastAPI application

# HTTPSRedirectMiddleware

The `HTTPSRedirectMiddleware` enforces HTTPS by redirecting all incoming HTTP requests to HTTPS. This is essential for security in production environments.

## Usage

```python theme={null}
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

app.add_middleware(HTTPSRedirectMiddleware)
```

## Parameters

This middleware does not take any configuration parameters. It automatically redirects all HTTP requests to their HTTPS equivalent.

## How It Works

The middleware:

1. Checks if the incoming request is using HTTP (not HTTPS)
2. If HTTP, constructs the HTTPS equivalent URL
3. Returns a 307 Temporary Redirect response to the HTTPS URL
4. If already HTTPS, passes the request through normally

## Redirect Behavior

* **Status Code**: Uses 307 Temporary Redirect to preserve the HTTP method
* **URL Preservation**: Maintains the full path, query parameters, and fragment
* **Port Handling**: Automatically handles port numbers in the URL

## Examples

### Basic Usage

```python theme={null}
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

app.add_middleware(HTTPSRedirectMiddleware)

@app.get("/")
async def root():
    return {"message": "This endpoint is only accessible via HTTPS"}
```

With this configuration:

* `http://example.com/` → `https://example.com/`
* `http://example.com/api/users?page=2` → `https://example.com/api/users?page=2`

### Conditional HTTPS Enforcement

```python theme={null}
import os
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

# Only enforce HTTPS in production
if os.getenv("ENVIRONMENT") == "production":
    app.add_middleware(HTTPSRedirectMiddleware)

@app.get("/")
async def root():
    return {"message": "Hello World"}
```

### Combined with Other Security Middleware

```python theme={null}
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()

# Enforce HTTPS first
app.add_middleware(HTTPSRedirectMiddleware)

# Then validate the host
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["example.com", "*.example.com"],
)

@app.get("/")
async def root():
    return {"message": "Secure endpoint"}
```

## Deployment Considerations

### Reverse Proxy/Load Balancer

If your application is behind a reverse proxy (nginx, Apache) or load balancer that terminates SSL:

1. **Option 1**: Handle HTTPS redirect at the proxy level (recommended)
2. **Option 2**: Ensure the proxy sets the `X-Forwarded-Proto` header so the middleware can detect the original scheme

```nginx theme={null}
# nginx configuration
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
```

### Cloud Platforms

Many cloud platforms handle HTTPS termination:

* **AWS ELB/ALB**: Terminates SSL at the load balancer
* **Google Cloud Load Balancer**: Terminates SSL at the load balancer
* **Azure Application Gateway**: Terminates SSL at the gateway
* **Heroku**: Automatically handles HTTPS routing

In these cases, you may not need `HTTPSRedirectMiddleware` as the platform handles it.

### Development Environment

Don't use this middleware in local development unless you've set up local SSL certificates:

```python theme={null}
import os
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

# Only in production
if os.getenv("ENVIRONMENT") == "production":
    app.add_middleware(HTTPSRedirectMiddleware)
```

## Security Best Practices

1. **Always use in production**: HTTPS protects data in transit
2. **HSTS Headers**: Consider adding HTTP Strict Transport Security headers
3. **Certificate Management**: Ensure your SSL certificates are valid and up-to-date
4. **Redirect at the edge**: When possible, handle redirects at the CDN or load balancer level for better performance

## HSTS (HTTP Strict Transport Security)

After implementing HTTPS redirects, consider adding HSTS headers to tell browsers to always use HTTPS:

```python theme={null}
from fastapi import FastAPI, Response
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()

app.add_middleware(HTTPSRedirectMiddleware)

@app.middleware("http")
async def add_hsts_header(request, call_next):
    response = await call_next(request)
    # Only add HSTS header for HTTPS requests
    if request.url.scheme == "https":
        response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
    return response
```

## Common Issues

### Redirect Loops

If you experience redirect loops:

* Check if your reverse proxy is configured correctly
* Ensure `X-Forwarded-Proto` header is set properly
* Verify SSL termination is happening at the expected layer

### Mixed Content Warnings

After enabling HTTPS:

* Update all internal links to use HTTPS or relative URLs
* Ensure external resources (CDNs, APIs) are also loaded via HTTPS
* Check browser console for mixed content warnings
