大网数据广告活动
网站运营与故障问答

NGINX - Rewrite .js.php file to .js

· 52CE 我爱测

I have a dynamically created file start.js.php?c=21 and I would like to rewrite it's extension (to start.js , with query params). Is that possible? Is that a good method having such a rewrite? Is wrong having query string ?c=21 o…

问题原文

原帖链接 · fiskolin · CC BY-SA 4.0

I have a dynamically created file start.js.php?c=21 and I would like to rewrite it's extension (to start.js, with query params).

  1. Is that possible?
  2. Is that a good method having such a rewrite?
  3. Is wrong having query string ?c=21 on file location (to populate from PHP file with given c attribute)?

I am trying to create rewrite with:

server {
    location ~ \.js.php$ {
        rewrite ^(.*)$ $1.js last;
    }
}

This is returning 404 error code.

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

If the underlying filename is script.js.php then it doesn't make sense to rewrite this to script.js - as that would result in a 404.

However, the directives you posted would seem to result in a 404 for a different reason, as they rewrite script.js.php to script.js.php.js.

Presumably, you want to link to script.js?c=21 and internally rewrite this to script.js.php?c=21 (the underlying file), thus hiding the .php file extension from users. In which case, try something like the following instead:

server {
    location ~ \.js$ {
        rewrite (.*) $1.php last;
    }
}

To answer your specific queries:

  1. Is that possible?

Yes, but the "reverse" is probably what you really want to be doing. (?)

  1. Is that a good method having such a rewrite?

It's OK. Presumably, you have a requirement to mix PHP and JavaScript?

  1. Is wrong having query string ?c=21 on file location (to populate from PHP file with given c attribute)?

I don't think there is necessarily anything wrong with this. Bear in mind that some caching proxies may ignore the query string, but I think that is mostly historic.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2018-10-26)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。