Scala/Play/Nginx: static resource routing
-
20-12-2019 - |
Question
I've got my Play app running:
http://localhost:9000
Nginx is proxy passing it to this url:
http://localhost/Demo/
I have a problem with static assets though. For instance, this asset in html template
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
is going to
http://localhost/assets/stylesheets/main.css
and obviously results in not being found. If I change it to this (add /Demo
in front of the url):
<link rel="stylesheet" media="screen" href="/Demo@routes.Assets.at("stylesheets/main.css")">
it will now correctly go to this url:
http://localhost/Demo/assets/stylesheets/main.css
My question is: how can I add this /Demo
to all my static assets without hard codding it into my templates? I prefer to solve this using Play's routing and limit changes done to nginx conf.
I've tried adding a url prefix into application.conf
like this
application.context="/Demo"
but that affected all urls not only the static ones, so not a solution. Any thoughts?
My stack: Play Framework 2.2.1 / Scala 2.10.3 / Java 8 64bit / Nginx 1.4.3 / Ubuntu 13.10 64bit
UPDATE: SOLUTION Thanks to @biesior for providing the Java version, I've converted it to scala:
package core
import controllers.routes
object Assets {
def at(path: String): String = {
"/Demo" + routes.Assets.at(path)
}
}
Solution
Just overwite the path using own implementation of assets (ie. in utils
package):
package utils;
import controllers.routes;
public class MyAssets {
public static String at(String path){
return "/Demo"+ routes.Assets.at(path).toString();
}
}
in templates:
<img src='@utils.MyAssets.at("images/logo.png")' alt="">
On the quite other hand, will target project also work in subdirectory ? If not it's just easier to use subdomains, it's possible also with localhost, just configure your nginx for that project to use ie.: http://demo.loc
instead od http://localhost/Demo
and add this 'domain' to your hosts
file