Rewrite: A Simple and Powerful URL Rewriter for Go
https://dribbble.com/shots/14681612-Golang-Gopher

Rewrite: A Simple and Powerful URL Rewriter for Go

Rewrite is a Go package that lets you rewrite URL paths, subdomains or hosts based on regular expressions. It is inspired by Apache’s mod_rewrite module and can be used as a middleware for?net/http-based servers.

Rewrite can help you achieve better SEO results by redirecting old or unwanted URLs to new ones, enforcing a primary subdomain, or simplifying complex URL structures.

How to Install Rewrite

To install Rewrite, you need to have Go installed on your system. Then, you can use the go get command to download and install the package:

$ go get github.com/kataras/rewrite        

How to Use Rewrite

You can load rewrite options in two ways:

1. Through code using the?New?function and?Handler?method. This way, you can handle parse errors and create rules programmatically.

2. Or through a YAML file using the?Load?function which returns a?func(http.Handler) http.Handler. This is the most common and simplest way. It panics on parse errors.

The syntax of the rewrite rules is:

REDIRECT_CODE_DIGITS PATTERN_REGEX TARGET_REPL        

Where:

-?REDIRECT_CODE_DIGITS?is the HTTP status code to use for the redirection, such as 301 (Moved Permanently) or 302 (Found).

-?PATTERN_REGEX?is the regular expression that matches the request URL path, subdomain or host.

-?TARGET_REPL?is the replacement string that contains the new URL path, subdomain or host.

For example:

301 /seo/(.*) /$1        

This rule redirects all requests from relative path?/seo/* to /*?using the 301 HTTP status code.

You can also use a special option called?PrimarySubdomain?to redirect all requests from the root domain to a specific subdomain, such as?www.

For example:

PrimarySubdomain: www        

This option redirects all requests from?example.com?to?www.example.com.

Examples

Let’s write a simple application that follows these redirect rules:


- Redirects `/seo/*` to `/*`

- Redirects `/docs/v12*` to `/docs`

- Redirects `/old (.*)` to `/`

- Redirects root domain requests to `www.`

The code would look like this:

package main

import (
  "net/http"

  "github.com/kataras/rewrite"
)

func main() {
  mux := http.NewServeMux()
  // […routes]
  // Load the redirect rules from a YAML file.
  redirects := rewrite.Load("redirects.yml")
  // Wrap the router with the rewrite middleware.
  http.ListenAndServe(":8080", redirects(mux))
}        

The YAML file would look like this:

RedirectMatch:
  # Redirects /seo/* to /*
  - 301 /seo/(.*) /$1
  # Redirects /docs/v12* to /docs
  - 301 /docs/v12(.*) /docs
  # Redirects /old (.*) to /
  - 301 /old(.*) /
# Redirects root domain requests to www.
PrimarySubdomain: www        

That’s it! Now you can test your application and see how it redirects the requests according to your rules.

You can find more examples in the `_examples` folder of the GitHub repository:?https://github.com/kataras/rewrite/tree/main/_examples

Conclusion

Rewrite is a handy package that lets you rewrite URLs in Go with ease. It is compatible with any net/http router or framework and supports regular expressions for flexible matching and replacing. It can help you improve your SEO performance by redirecting old or unwanted URLs to new ones, enforcing a primary subdomain, or simplifying complex URL structures.


If you want to learn more about Rewrite, you can check out its GitHub repository:?https://github.com/kataras/rewrite

I hope you enjoyed this article and found it useful. If you have any feedback or questions, feel free to leave a comment below. Thank you for reading! ??



要查看或添加评论,请登录

Gerasimos Maropoulos的更多文章

  • RFC: HTTP Wire Errors

    RFC: HTTP Wire Errors

    Overview This RFC proposes a standardized approach for handling and representing HTTP wire errors in a consistent and…

  • HTTP Method Override for Iris

    HTTP Method Override for Iris

    Introduction HTTP method override is a technique used to support clients that do not support certain HTTP methods such…

  • Request Body Limit Middleware for Iris

    Request Body Limit Middleware for Iris

    Overview The Iris Body Limit middleware is a powerful tool for controlling the size of incoming request bodies in your…

  • Basic Authentication Middleware for Iris

    Basic Authentication Middleware for Iris

    Overview The Basic Authentication middleware provides a robust and flexible way to secure your Iris web applications…

  • Request Rate Limiting Middleware for Iris

    Request Rate Limiting Middleware for Iris

    Overview The middleware provides rate limiting capabilities for the Iris web framework. It allows developers to control…

  • AccessLog Middleware for Iris

    AccessLog Middleware for Iris

    AccessLog Middleware for Iris The accesslog middleware for the Iris web framework provides detailed logging for…

  • How to use hCAPTCHA with Iris

    How to use hCAPTCHA with Iris

    In this article, we will learn how to use hCAPTCHA with Iris, a web framework for Go that provides fast and easy…

  • How to use JWT authentication with Iris

    How to use JWT authentication with Iris

    In this tutorial, we will learn how to use JWT (JSON Web Token) authentication with Iris, a fast and simple web…

  • How to use Iris and Basic authentication

    How to use Iris and Basic authentication

    Iris is a fast, simple yet fully featured and very efficient web framework for Go. It provides a beautifully expressive…

  • How to Use Iris and PostgreSQL for Web Development

    How to Use Iris and PostgreSQL for Web Development

    A guide to using PG middleware, a package for Iris that provides easy and type-safe access to PostgreSQL database. Iris…

社区洞察

其他会员也浏览了