【问题标题】:Rewrite URL to index.php using nginx server使用 nginx 服务器将 URL 重写为 index.php
【发布时间】:2021-06-29 15:42:12
【问题描述】:

我需要帮助来在 nginx 服务器上配置我的网站。早些时候我使用的是 apache,所以我使用 htaccess 在 index.php 上重定向。但我才知道 nginx 不支持 htaccess。我是 nginx 服务器的新手。让我通过例子更清楚地说明。

当我使用 apache 时,我的 htaccess 如下所示-

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ index.php [L]
</IfModule>

我现在需要在 nginx 服务器上做同样的事情。请任何人建议我如何做到这一点。我试图自己弄清楚并尝试了很多东西,但没有任何效果,例如-

我试过了-

location / {
    # Check if a file or directory index file exists, else route it to index.php.
    try_files $uri $uri/ /index.php;
}

我也尝试了这里建议的解决方案: How to enable URL rewrite in Ubuntu, nGinx and codeigniter?

location ~* \.php$ {
     fastcgi_pass unix:/run/php/php5.6-fpm.sock;
     root /var/www/html/;
     try_files $uri =404;
     fastcgi_index  index.php;
     fastcgi_param   SCRIPT_FILENAME $request_filename;
     include fastcgi_params;
     fastcgi_buffer_size 128k;
     fastcgi_buffers 256 4k;
     fastcgi_busy_buffers_size 256k;
     fastcgi_temp_file_write_size 256k;
}

我的要求是重写所有这些网址:

https://example.com/xyz 
https://example.com/abc
https://example.com/pqr

收件人

https://example.com/index.php

我的文件夹结构- folder-structer.png

提前致谢。

【问题讨论】:

    标签: php .htaccess nginx redirect mod-rewrite


    【解决方案1】:

    如果你只想在文件不存在时重写(而不是重定向)你应该使用“try_files”,例如:

    location / {
        try_files $uri $uri/ /index.php =404;
    }
    

    然后nginx会先测试请求是否映射到文件,如果映射到包含索引文件的目录,则在文档根目录中查找index.php。它将根据找到的内容解决请求。如果没有匹配,它将返回 404。

    【讨论】:

    • 嘿@code-a1,感谢您的回复。是的,我想重写 URL 不重定向抱歉混淆。我已经更新了我的问题。我也尝试了您的解决方案,但它似乎不起作用。知道我做错了什么吗?
    • @LyricxMint 文件 index.php 存在并且您正在编辑正确的文件?与 apache 不同,你不需要在目录中创建一个 .htaccess 文件
    • @code-1 index.php 文件在那里。我正在我的 /etc/nginx/sites-available/default 文件中进行所有更改实际上我的基本 url 工作正常,请参阅此处 thexdownloader.com。但是,当我尝试访问子 url 链接时,它无法正常工作:thexdownloader.com/tiktok-video-downloader。请推荐?
    • 子网址不起作用,因为没有文件:您使用的是 laravel 还是类似的框架?如果不是,您必须创建一个名为“tiktok-video-downloader”的文件夹,并在此处插入 index.php 文件
    • @code-1 不,我没有使用 laravel。它是一个简单的核心 php。你在说什么你的意思是说我需要为每个网址创建 index.php?我正在处理来自位于根文件夹中的单个 index.php 的所有请求。所以我只需要将每个请求 url 重写为 index.php。
    猜你喜欢
    • 2022-08-19
    • 2021-05-08
    • 1970-01-01
    • 2011-09-16
    • 2013-03-12
    • 1970-01-01
    • 2013-06-25
    • 2012-04-29
    • 1970-01-01
    相关资源
    最近更新 更多