Absolute vs Relative Urls
I Would Like to Know the Differences Between These Two Types of Urls: Relative Urls (For Pictures, Css Files, Js Files, Etc.) and Absolute Urls. in Addition...
I would like to know the differences between these two types of URLs: relative URLs (for pictures, CSS files, JS files, etc.) and absolute URLs.
In addition, which one is better to use?
12 Answers
Should I use absolute or relative URLs?
If by absolute URLs you mean URLs including scheme (e.g. http / https) and the hostname (e.g. yourdomain.com) don't ever do that (for local resources) because it will be terrible to maintain and debug.
Let's say you have used absolute URL everywhere in your code like <img src="">. Now what will happen when you are going to:
- switch to another scheme (e.g. http -> https)
- switch domain names (test.yourdomain.com -> yourdomain.com)
In the first example what will happen is that you will get warnings about unsafe content being requested on the page. Because all your URLs are hardcoded to use http(://). And when running your pages over https the browser expects all resources to be loaded over https to prevent leaking of information.
In the second example when putting your site live from the test environment it would mean all resources are still pointing to your test domain instead of your live domain.
So to answer your question about whether to use absolute or relative URLs: always use relative URLs (for local resources).