Rewriting Next.js with custom headers

My web app allows users to create their own profiles with custom usernames, which can be accessed via the following URLs.

ourplatform.com/john
ourplatform.com/john/about
ourplatform.com/john/contact

ourplatform.com/jane
ourplatform.com/jane/about
ourplatform.com/jane/contact

Users also have the option to link their domain names to their profiles, resulting in URLs structured like this.

john.com
john.com/about
john.com/contact

jane.com
jane.com/about
jane.com/contact

Here is an excerpt from my next.config.js file.

module.exports = {
  async rewrites () {
    return [
      {
        source: '/:path*',
        has: [
          {
            type: 'header',
            key: 'x-username',
            value: '(?<username>.*)'
          }
        ],
        destination: '/:username/:path*'
      }
    ]
  }
}

In addition, here is the relevant Nginx configuration.

server {
  listen 80;
  server_name john.com;

  add_header x-username "john";
  proxy_set_header x-username "john";

  location /_next {
    proxy_pass http://127.0.0.1:1323;
  }

  location = / {
    proxy_pass http://127.0.0.1:1323/john;
  }

  location / {
    proxy_pass http://127.0.0.1:1323/john$request_uri;
  }
}

Despite these configurations, I am encountering a 404 error on the linked domains. Can anyone pinpoint what might be causing this issue?

Answer №1

Consider using host matching as an alternate approach which is explained in detail here

module.exports = {
  async rewrites() {
    return [
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'john.com' }],
        destination: '/john/:path*',
      },
      {
        source: '/:path*',
        has: [{ type: 'host', value: 'jane.com' }],
        destination: '/jane/:path*',
      },
    ]
  },
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

Guide to transforming a JSON file value into a JavaScript list

I need assistance with converting a string of comma-separated values in a JSON file into a list. The goal is to iterate through the list in a for loop and click on each element. Can you help me with this task? testdata.json : {"optionsList":&quo ...

Troubleshooting: Why are my images not displaying in webpack and node.js setup?

My problem: I'm facing an issue with background images in my project. I have included two images and used file-loader to bundle them through webpack. While the images display correctly in the app during development using webpack-dev-server, they disap ...

Is there a way to assign a variable as the value for the jQuery .attr method?

How can I use jQuery's attr() method to pass a variable as the value for the 'src' attribute? Here is an example of what I am trying to achieve: var under700 = 'image.jpg' $('.two_images img').attr('src', (und ...

The publicPath configuration in Webpack is not functioning as expected

Check out my demo setup: Take a look at my webpack configuration below: module.exports = { entry: './app.js', output: { filename: 'bundle.js', path: './build', publicPath: 'http://localhost:3000/&apos ...

Utilize Node.js to sort through data

One API is providing me with this type of response. I need to extract the latitude and longitude of a single entity. How can I filter this data using JavaScript (Node.js)? header { gtfs_realtime_version: "1.0" incrementality: FULL_DATASET timestamp: ...

Error message: Laravel unable to locate requested page

Attempting to make a post request using AngularJS in Laravel, I encountered the following error message: Oops! The page you are trying to access could not be found. JAVASCRIPT app.controller('main',['$scope','$http',&apos ...

Sending a properly formatted string on Postman

My website allows users to answer coding problems. I am looking to store the questions and answers in a mongodb database. However, when testing the routes on my express application, I am encountering difficulties in sending formatted text in the request to ...

The Next.js webhook is sending back a 301 (redirect) status code instead of the expected 200

I've encountered an issue with my Next.js app where I set up an endpoint to handle webhooks from a third-party payment application. The logic in the code for this endpoint is straightforward - it verifies that the order has been paid and then updates ...

Determine the Height of the Container once the Font File has Finished Loading

When styling a website with a unique font using @font-face, the browser must download the font file before it can display the text correctly, similar to how it downloads CSS and JavaScript files. This poses an issue in Chrome (v16.0.912.63) and Safari (v5 ...

AngularJS filtering with multiple conditions

My ng-repeat list is currently displaying a collection of objects with a filter applied to only show objects inserted today. Here is how it looks: <div class="row msf-row" ng-repeat="record in recordlist | filter: record.date = dateJson"> Whi ...

Would it be frowned upon in JavaScript to use "if (somestring in {'oneoption':false, 'secondoption':false})"?

Is the use of this construct considered a bad practice in JavaScript and could it lead to unexpected behavior? if (e.target.name in {name: '', number: ''}) { // do something } This code checks if the 'name' attribute of an ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

Techniques for Extracting the Values of all ng-models within an ng-repeat Loop

How do I retrieve the total value of all ng-models within an ng-repeat loop using AngularJS? Below is my HTML code: <div ng-repeat="kind in plans.availableOptions"> <span class="payLabel text-left">{{kind.name}}</span> ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

Validating a model in Mongoose: Best practices for updating data

I am facing an issue with my model. It seems that while creating, incorrect information is prohibited, but when editing, it is allowed. How can I prevent this from happening? var userSchema = new Schema({ cartaoCidadao: { type: String, require ...

Locate the position of a substring within a Uint8Array

I'm working with a Uint8Array that contains the content of a PDF file. My goal is to locate a specific string within this array in order to insert additional content at that particular position. My current approach involves converting the Uint8Array ...

Configuring headless unit testing with requirejs

Seeking a JavaScript unit testing environment, I feel like I'm on a quest for the Holy Grail. The criteria are as follows: testing Requirejs AMD modules isolating each module by mocking out dependencies ability to test in-browser during development ...

Controlling opacity with jQuery animate() function using a click event

I have a specific requirement for an animation. When the button is clicked, I need the element to transition from 0 opacity to full 1 opacity within 300 milliseconds. The issue I am facing is that when the button is clicked, the animation does not work a ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...