rewrites

Yeniden yazmalar, gelen bir istek yolunu farklı bir hedef yolla eşlemenize olanak tanır.

Yeniden yazmalar bir URL proxy'si olarak hareket eder ve hedef yolu maskeleyerek kullanıcının sitedeki konumunu değiştirmemiş gibi görünmesini sağlar. Bunun aksine, yönlendirmeler yeni bir sayfaya yönlendirir ve URL değişikliklerini gösterir.

Yeniden yazmaları kullanmak için next.config.js adresindeki rewrites tuşunu kullanabilirsiniz:

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/about',
        destination: '/',
      },
    ]
  },
}

Yeniden yazmalar istemci tarafı yönlendirmeye uygulanır, bir <Link href="/about"> yukarıdaki örnekte uygulanan yeniden yazmaya sahip olacaktır.

rewrites source ve destination özelliklerine sahip nesneler içeren bir dizi veya dizilerden oluşan bir nesne (aşağıya bakın) döndürmeyi bekleyen bir asenkron işlevdir:

rewrites işlevi bir dizi döndürdüğünde, yeniden yazmalar dosya sistemi (sayfalar ve /public dosyaları) kontrol edildikten sonra ve dinamik rotalardan önce uygulanır. rewrites işlevi belirli bir şekle sahip bir dizi nesnesi döndürdüğünde, Next.js'nin v10.1 adresinden itibaren bu davranış değiştirilebilir ve daha hassas bir şekilde kontrol edilebilir:

next.config.js
module.exports = {
  async rewrites() {
    return {
      beforeFiles: [
        // These rewrites are checked after headers/redirects
        // and before all files including _next/public files which
        // allows overriding page files
        {
          source: '/some-page',
          destination: '/somewhere-else',
          has: [{ type: 'query', key: 'overrideMe' }],
        },
      ],
      afterFiles: [
        // These rewrites are checked after pages/public files
        // are checked but before dynamic routes
        {
          source: '/non-existent',
          destination: '/somewhere-else',
        },
      ],
      fallback: [
        // These rewrites are checked after both pages/public files
        // and dynamic routes are checked
        {
          source: '/:path*',
          destination: `https://my-old-site.com/:path*`,
        },
      ],
    }
  },
}

Bilmekte fayda var: beforeFiles adresindeki yeniden yazmalar, bir kaynakla eşleştikten hemen sonra dosya sistemini/dinamik rotaları kontrol etmez, tüm beforeFiles kontrol edilene kadar devam eder.

Next.js rotalarının kontrol edilme sırası şöyledir:

  1. başlıklar kontrol edilir/uygulanır
  2. yönlendirmeler kontrol edilir/uygulanır
  3. beforeFiles yeniden yazmalar kontrol edilir/uygulanır
  4. genel dizindeki statik dosyalar, _next/static dosyaları ve dinamik olmayan sayfalar kontrol edilir/servis edilir
  5. afterFiles yeniden yazmalar kontrol edilir/uygulanır, bu yeniden yazmalardan biri eşleşirse, her eşleşmeden sonra dinamik rotaları/statik dosyaları kontrol ederiz
  6. fallback yeniden yazmalar kontrol edilir/uygulanır, bunlar 404 sayfası oluşturulmadan önce ve dinamik rotalar/tüm statik varlıklar kontrol edildikten sonra uygulanır. getStaticPaths adresinde fallback: true/'blocking' kullanırsanız, next.config.js adresinizde tanımlanan fallback rewrites çalıştırılmayacaktır.

Rewrite parameters

Bir yeniden yazmada parametreler kullanıldığında, parametrelerin hiçbiri destination adresinde kullanılmadığında parametreler varsayılan olarak sorguda geçirilecektir.

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-about/:path*',
        destination: '/about', // The :path parameter isn't used here so will be automatically passed in the query
      },
    ]
  },
}

Hedefte bir parametre kullanılırsa, parametrelerin hiçbiri sorguda otomatik olarak geçirilmeyecektir.

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/docs/:path*',
        destination: '/:path*', // The :path parameter is used here so will not be automatically passed in the query
      },
    ]
  },
}

Hedefte zaten bir sorgu kullanılmışsa, sorguyu destination adresinde belirterek parametreleri sorguda manuel olarak geçirebilirsiniz.

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/:first/:second',
        destination: '/:first?second=:second',
        // Since the :first parameter is used in the destination the :second parameter
        // will not automatically be added in the query although we can manually add it
        // as shown above
      },
    ]
  },
}

Bilmekte fayda var: Otomatik Statik Optimizasyondan gelen statik sayfalar veya yeniden yazmalardan gelen ön oluşturma paramları, hidrasyondan sonra istemcide ayrıştırılacak ve sorguda sağlanacaktır.

Path Matching

Yol eşleşmelerine izin verilir, örneğin /blog/:slug, /blog/hello-world ile eşleşir (iç içe geçmiş yollar yoktur):

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog/:slug',
        destination: '/news/:slug', // Matched parameters can be used in the destination
      },
    ]
  },
}

Wildcard Path Matching

Bir joker karakter yolunu eşleştirmek için bir parametreden sonra * kullanabilirsiniz; örneğin /blog/:slug*, /blog/a/b/c/d/hello-world ile eşleşecektir:

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog/:slug*',
        destination: '/news/:slug*', // Matched parameters can be used in the destination
      },
    ]
  },
}

Regex Path Matching

Bir regex yolunu eşleştirmek için regex'i bir parametreden sonra parantez içine alabilirsiniz; örneğin /blog/:slug(\\d{1,}), /blog/123 ile eşleşir ancak /blog/abc ile eşleşmez:

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/old-blog/:post(\\d{1,})',
        destination: '/blog/:post', // Matched parameters can be used in the destination
      },
    ]
  },
}

Aşağıdaki karakterler (, ), {, }, :, *, +, ? regex yol eşleştirmesi için kullanılır, bu nedenle source içinde özel olmayan değerler olarak kullanıldıklarında önlerine \\ eklenerek kaçılmalıdır:

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        // this will match `/english(default)/something` being requested
        source: '/english\\(default\\)/:slug',
        destination: '/en-us/:slug',
      },
    ]
  },
}

Yalnızca başlık, çerez veya sorgu değerleri de has alanıyla eşleştiğinde veya missing alanıyla eşleşmediğinde bir yeniden yazmayı eşleştirmek için kullanılabilir. Yeniden yazmanın uygulanabilmesi için hem source hem de tüm has öğelerinin eşleşmesi ve tüm missing öğelerinin eşleşmemesi gerekir.

has ve missing öğeleri aşağıdaki alanlara sahip olabilir:

next.config.js
module.exports = {
  async rewrites() {
    return [
      // if the header `x-rewrite-me` is present,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the header `x-rewrite-me` is not present,
      // this rewrite will be applied
      {
        source: '/:path*',
        missing: [
          {
            type: 'header',
            key: 'x-rewrite-me',
          },
        ],
        destination: '/another-page',
      },
      // if the source, query, and cookie are matched,
      // this rewrite will be applied
      {
        source: '/specific/:path*',
        has: [
          {
            type: 'query',
            key: 'page',
            // the page value will not be available in the
            // destination since value is provided and doesn't
            // use a named capture group e.g. (?<page>home)
            value: 'home',
          },
          {
            type: 'cookie',
            key: 'authorized',
            value: 'true',
          },
        ],
        destination: '/:path*/home',
      },
      // if the header `x-authorized` is present and
      // contains a matching value, this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-authorized',
            value: '(?<authorized>yes|true)',
          },
        ],
        destination: '/home?authorized=:authorized',
      },
      // if the host is `example.com`,
      // this rewrite will be applied
      {
        source: '/:path*',
        has: [
          {
            type: 'host',
            value: 'example.com',
          },
        ],
        destination: '/another-page',
      },
    ]
  },
}

Rewriting to an external URL

Examples

Yeniden yazmalar, harici bir url'ye yeniden yazmanıza olanak tanır. Bu özellikle Next.js'yi aşamalı olarak benimsemek için kullanışlıdır. Aşağıda, ana uygulamanızın /blog rotasını harici bir siteye yönlendirmek için örnek bir yeniden yazma verilmiştir.

next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/blog',
        destination: 'https://example.com/blog',
      },
      {
        source: '/blog/:slug',
        destination: 'https://example.com/blog/:slug', // Matched parameters can be used in the destination
      },
    ]
  },
}

trailingSlash: true adresini kullanıyorsanız, source parametresine de bir sondaki eğik çizgi eklemeniz gerekir. Hedef sunucu da sonda eğik çizgi bekliyorsa, destination parametresine de eklenmelidir.

next.config.js
module.exports = {
  trailingSlash: true,
  async rewrites() {
    return [
      {
        source: '/blog/',
        destination: 'https://example.com/blog/',
      },
      {
        source: '/blog/:path*/',
        destination: 'https://example.com/blog/:path*/',
      },
    ]
  },
}

Incremental adoption of Next.js

Ayrıca Next.js'nin tüm Next.js rotalarını kontrol ettikten sonra mevcut bir web sitesine proxy göndermeye geri dönmesini sağlayabilirsiniz.

Bu şekilde, Next.js'ye daha fazla sayfa taşırken yeniden yazma yapılandırmasını değiştirmeniz gerekmez

next.config.js
module.exports = {
  async rewrites() {
    return {
      fallback: [
        {
          source: '/:path*',
          destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
        },
      ],
    }
  },
}

Rewrites with basePath support

Yeniden yazımlarla basePath desteğinden yararlanırken, yeniden yazıma basePath: false eklemediğiniz sürece her source ve destination 'nin önüne otomatik olarak basePath eklenir:

next.config.js
module.exports = {
  basePath: '/docs',
 
  async rewrites() {
    return [
      {
        source: '/with-basePath', // automatically becomes /docs/with-basePath
        destination: '/another', // automatically becomes /docs/another
      },
      {
        // does not add /docs to /without-basePath since basePath: false is set
        // Note: this can not be used for internal rewrites e.g. `destination: '/another'`
        source: '/without-basePath',
        destination: 'https://example.com',
        basePath: false,
      },
    ]
  },
}

Rewrites with i18n support

Yeniden yazmalarla i18n desteğinden yararlanırken, yeniden yazmaya locale: false eklemediğiniz sürece her source ve destination yapılandırılmış locales 'u işlemek için otomatik olarak öneklenir. locale: false kullanılıyorsa, doğru şekilde eşleşmesi için source ve destination 'nin önüne bir yerel ayar eklemelisiniz.

next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr', 'de'],
    defaultLocale: 'en',
  },
 
  async rewrites() {
    return [
      {
        source: '/with-locale', // automatically handles all locales
        destination: '/another', // automatically passes the locale on
      },
      {
        // does not handle locales automatically since locale: false is set
        source: '/nl/with-locale-manual',
        destination: '/nl/another',
        locale: false,
      },
      {
        // this matches '/' since `en` is the defaultLocale
        source: '/en',
        destination: '/en/another',
        locale: false,
      },
      {
        // it's possible to match all locales even when locale: false is set
        source: '/:locale/api-alias/:path*',
        destination: '/api/:path*',
        locale: false,
      },
      {
        // this gets converted to /(en|fr|de)/(.*) so will not match the top-level
        // `/` or `/fr` routes like /:path* would
        source: '/(.*)',
        destination: '/another',
      },
    ]
  },
}

Version History

VersionChanges
v13.3.0missing added.
v10.2.0has added.
v9.5.0Headers added.