阿里云主机折上折
  • 微信号
Current Site:Index > Force HTTPS (HSTS)

Force HTTPS (HSTS)

Author:Chuan Chen 阅读数:63157人阅读 分类: 前端安全

What is HSTS

HSTS (HTTP Strict Transport Security) is a security policy mechanism that forces browsers to use HTTPS when establishing connections with servers. It is implemented through the Strict-Transport-Security response header, instructing browsers to access the website only via HTTPS for a specified duration. Even if users manually enter an HTTP address, it will be automatically redirected to HTTPS.

Why HSTS is Needed

The HTTP protocol has inherent security risks due to plaintext transmission, making data vulnerable to eavesdropping or tampering. While HTTPS resolves these issues, users may still initially connect via HTTP during their first visit, leaving room for attacks. HSTS enhances security in the following ways:

  1. Prevents SSL Stripping Attacks: Attackers may intercept HTTP requests and block HTTPS upgrades.
  2. Avoids Mixed Content Issues: Ensures all resources are loaded over secure connections.
  3. Reduces Man-in-the-Middle Risks: Enforces encrypted communication for all traffic.

How HSTS Works

When a browser first visits an HSTS-enabled website, the server responds with a Strict-Transport-Security header. The browser records this information and automatically upgrades HTTP to HTTPS for subsequent visits.

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

This response header includes three key parameters:

  • max-age: The validity period of the HSTS policy (in seconds).
  • includeSubDomains: Applies the policy to all subdomains if enabled.
  • preload: Indicates the website wishes to be included in browser preload lists.

Implementing HSTS

Server Configuration Examples

Nginx Configuration:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

Apache Configuration:

Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

Node.js Express Example:

const express = require('express');
const helmet = require('helmet');
const app = express();

app.use(helmet.hsts({
  maxAge: 31536000,
  includeSubDomains: true,
  preload: true
}));

Frontend HSTS Status Detection

JavaScript can check if the current page was loaded via HSTS:

if (window.location.protocol === 'https:') {
  console.log('Page loaded via HTTPS');
  
  // Check for HSTS
  fetch(window.location.href, { method: 'HEAD' })
    .then(response => {
      const hstsHeader = response.headers.get('Strict-Transport-Security');
      if (hstsHeader) {
        console.log('HSTS enabled:', hstsHeader);
      }
    });
}

HSTS Preload List

Browsers maintain an HSTS preload list of websites that enforce HTTPS. To join this list:

  1. Ensure the root domain and all subdomains support HTTPS.
  2. Redirect all HTTP traffic to HTTPS.
  3. Include all subdomains in the HSTS policy.
  4. Submit an application at hstspreload.org.
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

HSTS Considerations

  1. First Visit Issue: Users may still connect via HTTP during their first visit.
  2. Certificate Error Handling: HSTS prevents users from bypassing certificate warnings.
  3. Rollback Difficulty: Once deployed, revocation is challenging during the max-age period.
  4. Testing Environments: Use cautiously in development to avoid complications.

Solving Development Environment Issues

For local development:

  1. Use self-signed certificates and manually trust them.
  2. Configure HTTPS for localhost.
  3. Temporarily disable HSTS:
    • Chrome: Visit chrome://net-internals/#hsts.
    • Firefox: Clear HSTS information from history.
# Generate a self-signed certificate
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

Combining HSTS with Other Security Headers

HSTS is often used alongside other security headers for layered protection:

Content-Security-Policy: default-src https: 'unsafe-inline' 'unsafe-eval'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Case Study

An e-commerce site after deploying HSTS:

  1. First visit to http://example.com is 301-redirected to https://example.com.
  2. The server returns an HSTS header with a 1-year validity.
  3. Subsequent visits automatically upgrade http://example.com to https://example.com.
  4. All subdomains (e.g., cdn.example.com) also enforce HTTPS.

Performance Considerations

HSTS can improve performance:

  1. Reduces HTTP-to-HTTPS redirects.
  2. Enables TLS session resumption and OCSP stapling.
  3. Supports HTTP/2, which requires HTTPS.
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_stapling on;
ssl_stapling_verify on;

Browser Compatibility

Modern browsers widely support HSTS:

  • Chrome 4+
  • Firefox 4+
  • Safari 7+
  • Edge 12+
  • Opera 12+

Check detailed support at caniuse.com.

Monitoring and Reporting

HSTS supports reporting for policy violations:

Strict-Transport-Security: max-age=31536000; includeSubDomains; report-uri="https://example.com/hsts-report"

The reporting endpoint must handle JSON-formatted reports:

app.post('/hsts-report', (req, res) => {
  const report = req.body;
  console.log('HSTS violation report:', report);
  // Store or analyze the report
  res.status(204).end();
});

Deployment Strategy Recommendations

  1. Start with a short max-age (e.g., 300 seconds) for testing.
  2. Gradually increase max-age to 1 year or longer.
  3. Add includeSubDomains only after confirming all subdomains support HTTPS.
  4. Finally, consider joining the preload list.
# Testing phase
Strict-Transport-Security: max-age=300

# Production
Strict-Transport-Security: max-age=31536000; includeSubDomains

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.