短链接服务的 Nginx 配置:如果不是文件则重写 [英] Nginx configuration for shortlink service: Rewrite if not file

查看:54
本文介绍了短链接服务的 Nginx 配置:如果不是文件则重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前段时间我开发了一个短链接服务(比如 goo.gl).

Some time ago I developed a shortlink service (like goo.gl).

浏览器地址栏中的短链接显示为example.com/Lg1Q

Shortlinks in the browsers addressbar are displayed as example.com/Lg1Q

由于性能优势,我最近从 Lighty 迁移到 Nginx.在 Lighttpd 中我使用了

Recently I migrated from Lighty to Nginx, due to performance benefits. In Lighttpd I used

url.rewrite-if-not-file = (
    "^/(.*)(\?.*)?$" => "/index.php?fwd=$1"
)

将 URL 中的Lg1Q"部分交给 index.php 脚本.

to hand over the "Lg1Q" part from the URL to the index.php script.

index.php 脚本处理来自 URL 的非文件部分,如下所示:

The index.php script processes the not-file-part from the URL as follows:

if ( !empty( $myUrl ) && $_SERVER['REQUEST_URI'] !== '/index.php' && $_SERVER['REQUEST_URI'] !== '/index.html' && $_SERVER['REQUEST_URI'] !$

        $query = htmlspecialchars( str_replace("fwd=","", $_SERVER['QUERY_STRING']) );
        require_once 'src/clsForwardURL.class.php';
        $myForward = new clsForwardURL();
        $url = $myForward->fForwardURL( $query );
        $url = ( $url[0]['su_longurl'] );
        echo header( 'location:'.$url );


}//end if

我尝试将重写规则从 Lighttpd 重建为 Nginx 语法,例如:

I tried to rebuild the rewrite rule from Lighttpd to Nginx syntax like:

rewrite "^/(.*)(\?.*)?$" /index.php?fwd=$1;

之后,我随后在/etc/nginx/sites中nginx宿主容器的location ~ \.php块和location/块中插入了这条规则- 可用.

After that, I inserted this rule subsequently in the location ~ \.php block and the location / block of the nginx host container in /etc/nginx/sites-available.

不幸的是,在这两种情况下,浏览器都显示了404"或500"错误.

Unfortunally in both cases the browser showed a '404' or a '500' error.

我的问题是:如何为短链接"目的正确设置重写规则?

My question is: How can I properly setup the rewrite rule for the 'shortlink' purpose?

推荐答案

location/ 块中的 rewrite 将重写所有内容 - 不仅仅是您的短 URI.您可以使用 try_files 语句限定重写操作.请参阅本文档了解更多信息.

The rewrite in the location / block will rewrite everything - not just your short URIs. You could qualify the rewrite operation using a try_files statement. See this document for more.

例如:

location / {
    try_files $uri $uri/ @rewrite;
}
location @rewrite {
    rewrite ^/(.*)$ /index.php?fwd=$1 last;
}

请注意,查询字符串组件不是 rewrite 指令使用的规范化 URI 的一部分.请参阅本文档了解更多信息.

Notice that the query string component is not part of the normalised URI used by the rewrite directive. See this document for more.

如果您修改 PHP 代码以接受 fwd 参数中的前导 /,您可以进一步简化上述内容,在这种情况下,您可以使用:

You can simplify the above further, if you modify the PHP code to accept a leading / in the fwd parameter, in which case you could use:

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

这篇关于短链接服务的 Nginx 配置:如果不是文件则重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆