【问题标题】:Is there a way to create a friendly url like site.com/state/127 and still point to a particular file like index.php有没有办法创建一个友好的 url 像 site.com/state/127 并且仍然指向一个特定的文件像 index.php
【发布时间】:2026-01-27 12:40:01
【问题描述】:

我正在创建一个 rest api 端点来将数据输入数据库。我一直在尝试将 url 重写为这种格式http://example.com/src/public/endpoint/data。 url 中的 public 是一个文件夹,其中有一个 index.php 文件,所有 url 都将被路由到该文件,但它不起作用。下面是我的 .htaccess 代码。

RewriteEngine 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://example.com/src/public/index.php?path=$1 [NC,L,QSA]

当我期望example.com/src/public/state/127 时,我将链接地址http://example.com/src/public/?path=state/127&_=1579497796272 作为端点。我知道我做的不对,但我想不通。

【问题讨论】:

  • 什么不起作用?您输入的是什么地址,似乎提取了哪个地址?一般而言,URL 重写的想法是将“好的”URL(RewriteRule 的第一部分)重写为“真实的”URL(第二部分),而不是相反。

标签: php rest .htaccess endpoint


【解决方案1】:

试试这个:

RewriteEngine On
RewriteCond %{THE_REQUEST} \?path=(.*)&(.*)\sHTTP.*$
RewriteRule ^(.*)$ /src/public/%1? [L,R]
RewriteRule ^src/public/state/127 /src/public/?path=state/127&_=1579497796272 [L]

首先您应该在RewriteEngine 之后添加on,这意味着启用 mod_rewrite 。 第二行将捕获请求并获取查询字符串的一部分。 第三行将在外部将请求重定向为友好。 最后一行将在内部将一个新的重定向到正确的路径。

注意:如果没问题,把R改成R=301为永久重定向。

【讨论】:

    最近更新 更多