How To Add Static Routes In CentOS
There are numerous ways to add static routes in Linux (CentOS). The easiest way is via the terminal by using one of the following examples.
How to add a static route for a specific host in Linux.
route add -host 192.168.1.47 gw 192.168.10.1
route del -host 192.168.1.47 gw 192.168.10.1
How to add a static route for a specific network in Linux.
route add -net 192.168.1.0/24 gw 192.168.10.1
route del -net 192.168.1.0/24 gw 192.168.10.1
How to add a default gateway.
route add default gw 192.168.10.1
route del default gw 192.168.10.1
The best place to add the default gateway is in the file /etc/sysconfig/network which would then look something like the below.
NETWORKING=yes NETWORKING_IPV6=yes HOSTNAME=server.example.com GATEWAY=192.168.0.10
Also note that default gateways are added on a per interface level in their startup files located in /etc/sysconfig/network-scripts. Example: /etc/sysconfig/network-scripts/ifcfg-eth0
One of the places to add a static route so it is added each time you reboot the server is to add it to /etc/sysconfig/rc.local. Your rc.local file would then look something like the below.
#!/bin/sh # # This script will be executed *after* all the other init scripts. # You can put your own initialization stuff in here if you don't # want to do the full Sys V style init stuff. touch /var/lock/subsys/local # Static Routes /sbin/route add -net 192.168.1.0/24 gw 192.168.10.1 /sbin/route add -host 192.168.1.47 gw 192.168.10.1