0Pricing
Browser Extensions Development (Chrome & Edge) · Lezione

Reindirizzamento e riscrittura degli URL

Scoprite come reindirizzare le richieste di rete verso URL diversi o riscrivere parti degli URL in base a criteri definiti.

Reindirizzamento e riscrittura degli URL è una lezione Browser Extensions Development (Chrome & Edge) gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Browser Extensions Development (Chrome & Edge), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Browser Extensions Development (Chrome & Edge) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Intro to URL Magic

Welcome! In this lesson, we'll learn how browser extensions can change where network requests go or how their URLs look.

  • Redirecting sends a request to a completely different URL.
  • Rewriting modifies parts of the original URL before it's processed.

Both are powerful tools for controlling web traffic using the `declarativeNetRequest` API.

Why Redirect or Rewrite?

Modifying URLs can serve many useful purposes:

  • Enforce HTTPS: Automatically upgrade insecure HTTP connections.
  • Fix broken links: Redirect old URLs to new ones.
  • Clean up URLs: Remove unnecessary tracking parameters.
  • Block unwanted content: Redirect specific requests to an empty page.

It helps improve security, privacy, and user experience.

The `redirect` Action Type

To redirect a network request, we use the `redirect` action type in our `declarativeNetRequest` rules. This action specifies a new URL or a pattern to generate one.

Here's a basic structure for a redirect rule:

{
  "id": 1,
  "priority": 1,
  "action": {
    "type": "redirect",
    "redirect": {
      "url": "https://new-example.com"
    }
  },
  "condition": {
    "urlFilter": "https://old-example.com/*"
  }
}

Simple URL Redirect Example

Let's say you want to redirect all requests to an old blog post URL to a new one. This rule tells the browser: 'If you see a request for old-blog.html, send it to new-blog-post.html instead.'

[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://www.example.com/new-blog-post.html"
      }
    },
    "condition": {
      "urlFilter": "https://www.example.com/old-blog.html"
    }
  }
]

Enforcing HTTPS with Redirects

A common use case is to ensure secure connections. You can redirect all HTTP requests for a specific domain to their HTTPS equivalent. This enhances user security by encrypting data.

This rule redirects any HTTP request for example.com to its HTTPS version.

[
  {
    "id": 2,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "transform": {
          "scheme": "https"
        }
      }
    },
    "condition": {
      "urlFilter": "http://example.com/*",
      "resourceTypes": ["main_frame", "sub_frame", "script", "image", "stylesheet"]
    }
  }
]

Introducing `regexSubstitution`

Sometimes you don't want to redirect to a fixed URL, but rather modify parts of the original URL. This is where regexSubstitution comes in. It uses regular expressions to match and replace parts of the URL.

The matched parts from the regexFilter in the condition can be referenced in the substitution string using backreferences like \1, \2, etc.

Rewriting URL Paths Example

Imagine you have old URLs like /users/123 and want them to become /profile/123. You can use regexSubstitution to capture the ID and rewrite the path.

This rule captures the number after /users/ and reuses it in the /profile/ path.

[
  {
    "id": 3,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "regexSubstitution": "https://www.example.com/profile/\\1"
      }
    },
    "condition": {
      "regexFilter": "^https://www.example.com/users/([0-9]+)$",
      "resourceTypes": ["main_frame"]
    }
  }
]

Modifying Query Parameters

regexSubstitution is great for cleaning up query parameters. You might want to remove a specific tracking parameter, like utm_source, from URLs to improve privacy or simplify sharing.

This rule matches URLs with ?utm_source=... and removes that parameter, keeping everything else.

[
  {
    "id": 4,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "regexSubstitution": "\\1"
      }
    },
    "condition": {
      "regexFilter": "^(https?://[^?]+)\\?utm_source=[^&]*(?:&(.*))?$",
      "resourceTypes": ["main_frame"],
      "excludedInitiatorDomains": ["example.com"]
    }
  }
]

Match Patterns & Regular Expressions

Remember, `urlFilter` uses match patterns, which are simpler for basic matches. `regexFilter` requires full regular expressions and is used when you need to capture parts of the URL for `regexSubstitution`.

  • Match Patterns: Wildcards like *, specific schemes/hosts.
  • Regular Expressions: Powerful pattern matching with groups () and special characters.

Choose the right tool for the job!

Redirect Challenge

Consider a rule designed to redirect all requests from http://insecure.com to https://secure.com. Which `redirect` action type is best suited for this goal?

Recap: Redirects & Rewrites

Great job! You've learned how to powerfully control network requests:

  • Redirects: Send requests to entirely new URLs using `redirect` with a `url`.
  • Rewrites: Modify parts of URLs using `redirect` with `transform` or `regexSubstitution`.
  • HTTPS enforcement: A practical use of `transform` to upgrade connections.
  • URL cleaning: Use `regexSubstitution` to remove or change parameters.

These techniques allow you to enhance security, fix issues, and customize user browsing experiences.

Domande Frequenti

La lezione «Reindirizzamento e riscrittura degli URL» è gratuita?

Sì — il testo completo di «Reindirizzamento e riscrittura degli URL» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Browser Extensions Development (Chrome & Edge), passa a CoddyKit PRO. Il corso Browser Extensions Development (Chrome & Edge) include 4 lezioni in totale.

Cosa imparerò in «Reindirizzamento e riscrittura degli URL»?

Scoprite come reindirizzare le richieste di rete verso URL diversi o riscrivere parti degli URL in base a criteri definiti. Eserciti Browser Extensions Development (Chrome & Edge) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Browser Extensions Development (Chrome & Edge)?

Non è richiesta alcuna esperienza precedente. Browser Extensions Development (Chrome & Edge) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Reindirizzamento e riscrittura degli URL»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Browser Extensions Development (Chrome & Edge)?

Sì. Ogni lezione Browser Extensions Development (Chrome & Edge) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Blocco delle richieste di rete
  2. Modifica delle intestazioni delle richieste
  3. Reindirizzamento e riscrittura degli URL
  4. Regole dinamiche e debugging di declarativeNetRequest
← Torna a Browser Extensions Development (Chrome & Edge)