To redirect mobile/smartphone traffic to the mobile version of a website using Nginx, you can use the if
directive in your Nginx configuration file.
Here’s an example configuration that redirects all mobile devices to a separate URL:
server {
listen 80;
server_name example.com;
root /var/www/example.com;
if ($http_user_agent ~* '(iPhone|iPod|blackberry|android.*mobile|windows.*phone)') {
return 302 http://m.example.com$request_uri;
}
# ... normal configuration
}
In this example, the if
directive matches the $http_user_agent
variable against a regular expression that includes common user-agent strings for mobile devices. If the user-agent string matches the regular expression, the request is redirected to the http://m.example.com
URL. If the user-agent string does not match, the request is processed as usual.
Note that you’ll need to replace example.com
with your actual domain name, and m.example.com
with the URL for your mobile site. Additionally, you may need to adjust the regular expression in the if
directive to match the user-agent strings for your target mobile devices.