Search code examples
linuxnginxasp.net-coreasp.net-core-mvcasp.net-core-1.1

asp.net core on linux with nginx routing doesn't work


I've created an ASP.NET Core MVC application and deployed it into Linux server. When I go to sitename.com browser shows up the Home/Index page without any problem.

But when I try to go sitename.com/Home/Index or another controller like sitename.com/Admin/Login nginx throws a 404 Not Found error. What should be the problem?

Here is my Startup.cs/Configure method.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Here is my website config from sites-available folder

server {
   listen 80 default_server;
   listen [::]:80 default_server ipv6only=on;

   root /var/www/sitename.com;
   index index.html index.htm;

   server_name sitename.com www.sitename.com;

   location / {
      try_files $uri $uri/ =404;
      proxy_pass http://127.0.0.1:5000;
   }

and nginx.conf

    user www-data;
    worker_processes 4;
    pid /run/nginx.pid;

    events {
        worker_connections 768;
    }

    http {

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
    }

    mail {

    }

Solution

  • Remove try_files $uri $uri/ =404; as it's testing if a certain url exists on the file system and if not return 404.

    But /Home/Index is a route, which do not map to an existing file but to controller action, hence you get the 404 error.