How to set domain and subdomain during the development stage for HTTP and HTTPS in Rails?
Resolving domain and subdomain issues is vital during the development stage, particularly for HTTP and HTTPS in Rails. In this context, nip.io
, a free wildcard DNS for any IP address, proves to be useful. It acts as a proxy, and when called upon (like so: 192.168.1.1.nip.io
), it navigates to your local network (in this case, 192.168.1.1
). Given these features, it doesn’t necessitate any amendments to your local hosts
file.
This setup is resourceful when there is a need for HTTPS with a valid domain that goes beyond localhost:3000
. It also aids in adding subdomains or integrating support with third-party APIs.
Configuring Your Rails Application
Implementation begins with updating your config/application.rb
by appending a new configuration line. The configuration amendment requires the addition of the domain to the app as an environmental variable. Here's how to do it:
# config/application.rb
module Multiauthappdevise
class Application < Rails::Application
config.hosts << ENV['ROOT_DOMAIN']
end
end
Afterward, run the Rails server using the following command:
ROOT_DOMAIN="$(ifconfig -l | xargs -n1 ipconfig getifaddr).nip.io:3000" rails s -b 0.0.0.0
The above command sets the ROOT_DOMAIN
environment to your local computer IP and then broadcast the server to 0.0.0.0
.
Consequently, launching your application with this command will make the app accessible via http://192.168.1.43.nip.io:3000
where 192.168.1.43
is your local computer's IP.
Enabling Local HTTPS
To turn on HTTPS locally, start by generating sample SSL certificates in your root app directory using OpenSSL as follows:
openssl req -new -newkey rsa:2048 -sha1 -days 365 -nodes -x509 -keyout .ssl/localhost.key -out .ssl/localhost.crt
This process is simple; all unnecessary details like country can be bypassed by merely hitting the enter key. Then execute the Rails server using this command:
ROOT_DOMAIN="$(ifconfig -l | xargs -n1 ipconfig getifaddr).nip.io:3000" rails s -b "ssl://0.0.0.0:3000?key=.ssl/localhost.key&cert=.ssl/localhost.crt"
Now, you can navigate to https://192.168.1.43.nip.io:3000
or a similar IP and click the Trust connection
button, located in a varying place depending on your browser. Note that in Chrome, you'll have to type thisisunsafe
when you see a warning about SSL.
How to check my local IP?
In order to check your local IP address on a Mac or Linux, you can type it into the console:
echo "$(ifconfig -l | xargs -n1 ipconfig getifaddr).nip.io:3000"
Summary
Setting up HTTP and HTTPS with subdomains can be tricky, but using this technique is fairly simple for development purposes and I believe that article makes your life easier.
Happy coding!