Next.JS - `.htaccess` 文件?

Next.JS - `.htaccess` file?

我刚刚开始使用我的第一个 Next.JS 应用程序。当我意识到我不确定如何使用 .htaccess 文件时,我使用了 npx create-next-app 并制作了几页。我已经习惯了 Apache 为我处理这些事情,并且简单地将我的 .htaccess 文件放入我的 Next.JS 应用程序的根目录中似乎并没有削减它。我将如何设置类似于以下内容的 .htaccess 文件?

RewriteEngine on

RewriteRule ^profile/([a-z0-9]+) profile.html

.htaccess 文件特定于 Apache,因此如果没有 Apache,您将无法使用它们。您可以使用 Apache as a proxy to your node.js app,但您仍然不会使用 .htaccess 文件;您可以在 Apache 配置中配置 RewriteRules,但是当您可以直接在应用程序逻辑中处理所有路由时就不需要了。

在 node.js 中,您不需要像 Apache 这样的单独 Web 服务器。您的程序可以很长-运行,绑定到一个端口,并监听和响应请求,这是网络服务器通常提供的主要功能。

Next.JS 在此处提供了用于设置自定义路由的文档:https://nextjs.org/docs/#custom-server-and-routing

如果您的服务器已经在使用 Apache 并且启用了 mod_rewrite,您可以使用此 .htaccess:

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

Source

你必须学会​​使用 pm2 :

  1. 您应该能够通过 ssl 在您的 ubuntu、centos 等中安装 nvm: 来自 https://github.com/nvm-sh/nvm
  2. nvm 将为您提供安装节点的可能性
  3. node安装完成后,全局安装pm2,
  4. https://pm2.keymetrics.io/
  5. 在项目的根目录创建文件:ecosystem.config.js

ecosystem.config.js :

module.exports = {
apps : [
    {
        name: "your_server_name",
        script: "./server.js",
        watch: true,
        env_development: {
            "PORT": 3000,
            "NODE_ENV": "development"
        },
        env_production: {
            "PORT": 8001,
            "NODE_ENV": "production",
        }
    }
]}

.htaccess 看起来像这样:

DirectoryIndex disabled
RewriteEngine On
RewriteRule ^$ http://127.0.0.1:8001/ [P,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://127.0.0.1:8001/ [P,L]

通过 SSH 登录您的站点:

ssh name@IP then password

如何 运行 pm2 .

pm2 start ecosystem.config.js --env production

pm2 start ecosystem.config.js --env development

服务器中需要哪些文件:

如果您在项目中使用下一个导出到 SSG .htaccess 文件将修复重定向问题

RewriteEngine On
RewriteRule ^([^/]+)/$ .html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ .html
RewriteRule ^([^/]+)/([^/]+)/$ //.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ // [R=301,L]